如何使用typescript基于角度4中的某些条件动态添加html标记的属性

时间:2018-01-09 17:34:45

标签: angular typescript angular-material2

我想添加mat-accordion的属性" displayMode"基于app组件中变量的值。

我正在使用ng-if来制作它。但我得到了错误。

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

如果我这样提供* ngIf =&#34; displayType&#34;然后displayMode =&#34; {{displayType}}&#34;,然后显示错误说

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/>

1 个答案:

答案 0 :(得分:3)

您无法使用*ngIf添加/删除属性,只能添加/删除元素。

我认为这是你正在寻找的东西:

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

attr.确保它实际上已添加到DOM中,而不是仅传递给组件类实例。

传递null会从元素中删除该属性。