0

The Angular AOT compiler does not fail when using a non existing property in a template if the usage is wrapped in an *ngIf directive.

E.g. in this example, custom does not have a property property defined:

<div *ngIf="condition">
  {{ custom.property }}
</div>

Why does the Angular compiler not fail on this code? Is there a way to instrument it to do so?

And just for clarification, it fails with this code as expected:

<div>
  {{ custom.property }}
</div>

I'm currently thinking of creating a custom lint script that would remove all *ngIfs from the code and do an AOT build to check that all properties do exist. Is that a valid idea? And if so, why do I have to do this in the first place?

I'm using Angular 5, but I think it doesn't work in newer versions either.

I found that the Angular Language service is able to report these errors (in VS Code or IntelliJ IDEA). So it should be possible.

3
  • Are you running with --prod flag? Commented Feb 27, 2019 at 0:05
  • You can dynamically add or delete properties, and most IDEs won't be able to check for these. There are some properties (added by Object.defineProperty for instance) that you can't check for in an AOT build. I don't think removing these is necessary. It seems a bit opinionated - what happens to the properties not wrapped in an *ngIf directive? Angular templating has an "safe navigation operator" syntax similar to Swift's optionals. You can rewrite your templates to use custom?.property, see angular.io/guide/… Commented Feb 27, 2019 at 9:03
  • My opinion: javascript itself is a versatile language, it's the developer's responsibility to ensure the variables are accessible. Angular provides a safe navigation operator to help, but it's the programmer's responsibility nevertheless Commented Feb 27, 2019 at 9:05

1 Answer 1

0

Angular actually provides this feature, but it's not turned on by default for whatever reason.

Adding the following code to tsconfig.json enables a full template type check:

"angularCompilerOptions": {
  "fullTemplateTypeCheck": true
}

But beware, this does not in fact do a "full" type check. It still skips over complex structural constructs. But in Ivy this will apparently be a feature that the compiler is able to do a proper "full" template type check.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.