Shreelakshmi G
Shreelakshmi G

Reputation: 119

how to dynamically add property for a html tag based on some condition in angular 4 using typescript

I want to add the property of mat-accordion "displayMode" based on the value given for a variable in app component.

I am using ng-if to make it. But Im getting error.

<mat-accordion class="accord-align" *ngIf="displayType" then displayMode="{{displayType}}" ><br/>
<<Some tags and text here>><br/>
</mat-accordion&gt;<br/>

If I provide like this *ngIf="displayType" then displayMode="{{displayType}}", then its showing error saying

compiler.es5.js:1694 Uncaught Error: Template parse errors:<><br/>
Parser Error: Bindings cannot contain assignments at column 30 in [displayType then displayMode={{displayType}}] in ng:///AppModule/AccordionComponent.html@1:38 ("&lt;div id="divi-align"&gt; <br/>
  &lt;mat-accordion class="accord-align" [ERROR -&gt;]*ngIf="displayType then displayMode={{displayType}}" &gt;
    &lt;mat-expansion-panel  class="panel1-align""): ng:///AppModule/AccordionComponent.html@1:38<br/>
Can't bind to '*ngIf' since it isn't a known property of 'mat-accordion'.<br/>
1. If 'mat-accordion' is an Angular component and it has '*ngIf' input, then verify that it is part of this module.<br/>
2. If 'mat-accordion' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.<br/>
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("&lt;div id="divi-align"&gt;
  &lt;mat-accordion class="accord-align" [ERROR -&gt;]*ngIf="displayType then displayMode={{displayType}}" &gt;
    &lt;mat-expansion-panel  class="panel1-align""): ng:///AppModule/AccordionComponent.html@1:38<br/>

Upvotes: 2

Views: 9149

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657416

You can't use *ngIf to add/remove attributes, only to add/remove elements.

I assume this is what you're looking for:

[attr.displayMode]="displayType ? displayType : null" 

attr. ensures that it is actually added to the DOM instead of only passed to a components class instance.

Passing null removes the attribute from the element.

Upvotes: 8

Related Questions