Hi I am trying to open modal page on page load in angular 13 I am using ElementRef to click a button on page load but I'm getting Property 'openCity' has no initializer and is not definitely assigned in the constructor.
please help me to fix this issue.
app.component.ts
@ViewChild('openCity') openCity:ElementRef;
ngOnInit(){
this.openCity.nativeElement.click();
}
app.component.html
<button id="openCity" #select_city [hidden]="false"
data-toggle="modal" data-target="#select_city">Open</button>
<div class="ltn__modal-area ltn__add-to-cart-modal-area">
<div class="modal fade" id="select_city" data-backdrop="static" tabindex="-1">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="ltn__quick-view-modal-inner">
<p>Modal Open</p>
</div>
</div>
</div>
</div>
</div>
</div>
CodePudding user response:
Change
@ViewChild('openCity') openCity: ElementRef;
to
@ViewChild('select_city') openCity!: ElementRef;
To fetch html elements angular uses its reference variables, not html ids.
Exclamation mark is to tell typescript that this variable will be initialized for sure, but later.
Error explanation
The error comes form ESLint/TSLint, that by default has set "strictPropertyInitialization": true
. This rule require to have all component variables to be initialized during declaration or in the constructor. Here you have variable openCity
, that is only declared, and it's value is set later by angular lifecycle. Typescript doesn't know that, so it is complaining. The exclamation mark just tells typescript that you are sure that the variable will have the value.
Alternatively you could set strictPropertyInitialization to false in the config, so it will disable this error in the wole project. I wouldn't recommend that, because at the end of the day, initializing variables at their declaration is a good practice (you can avoid many errors from undefined
variables by that).
CodePudding user response:
Just go to your tsconfig.json
and add this below code.
"strictPropertyInitialization": false
Hope it will resolve your issue.