如何使用打字稿根据angular 4中的某些条件为html标签动态添加属性

Shr*_*i G 2 typescript angular-material2 angular

我想根据为应用程序组件中的变量提供的值添加 mat-accordion "displayMode" 的属性。

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

<mat-accordion class="accord-align" *ngIf="displayType" then displayMode="{{displayType}}" ><br/>
<<Some tags and text here>><br/>
</mat-accordion&gt;<br/>
Run Code Online (Sandbox Code Playgroud)

如果我提供这样的 *ngIf="displayType" 然后 displayMode="{{displayType}}",那么它的显示错误说

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/>
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 6

您不能用于*ngIf添加/删除属性,只能用于添加/删除元素。

我想这就是你要找的:

[attr.displayMode]="displayType ? displayType : null" 
Run Code Online (Sandbox Code Playgroud)

attr. 确保它实际添加到 DOM 而不是只传递给组件类实例。

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