问题
Consider the following template:
<p>Hello, {{ name }}</p>
<button (click)="doLogin()">Login</button>
together with this TS-Class:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {}
Neither name
nor doLogin()
exist. Still it compiles and runs without error. Only when I try to click the button, I get the error message doLogin is not a function in the browser's console.
I do know, that this behaviour (errors on runtime) is mostly intended by Javascript. Nevertheless, I'd like to have as many errors shown as possible at compile time. Using Typescript does most of this work.
However, property bindings seem not to be evaluated at compile time. In my opinion, the Angular-Compiler should be capable of this. I tried setting fulltemplatetypecheck to true, but this didn't seem to do the trick. Tried it with ng serve
, ng build
and ng build --prod
.
Is there a way to detect non-existent property bindings while compiling? If not, is this an intended behaviour?
I'm using Angular 5.2.0, Typescript 2.5.3 and Angular CLI 1.6.4
回答1:
The feature will be available on angular 6. Based on the Issue.
We have a new compiler setting called fullTemplateTypeCheck (see https://github.com/angular/angular/blob/master/packages/compiler-cli/src/transformers/api.ts#L99) which will reveal this error.
This setting will become the default in Angular 6, and is highly recommended. We didn't turn in on in Angular 5 to not break existing users. I.e. the behavior you are seeing here is exactly what users saw in Angular 4.
Angular 6 Below
You can USE TS Lint to achieve this. I have used TS Lint with visual studio code to validate non-existent property bindings and methods.
It wont stop you from compiling but still show a error.
TS Lint will validate method,property
not found in the component
The angular CLI still compile your code successfully.
来源:https://stackoverflow.com/questions/49402769/can-i-make-the-angular-compiler-throw-an-error-when-a-non-existing-property-is-b