角度-单击按钮是否可以动态添加属性

Que*_*Que 10 angular

我在用什么

  • 角度的

我想做什么

  • 我有一个清单。当我按下按钮时,我想将一些自定义属性附加到某个HTML元素

是)我有的

  • 我的HTML清单

  • 与点击事件相关的按钮

我不确定该怎么办

  • 当我单击按钮时,以下属性将添加到“容器” div中:

[phantomOp] =“ myItems” [myOper] =“ oper”

的HTML

<div class="container">
  <ul>
    <li> Albums </li>
    <li> Dates </li>
    </ul>
</div>

<button (click)="addContainerAttributes"> Add Container Attributes </button>
Run Code Online (Sandbox Code Playgroud)

单击按钮后,我希望HTML看起来如何

<div class="container" [phantomOp]="myItems" [myOper]="oper">
  <ul>
    <li> Albums </li>
    <li> Dates </li>
  </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

TS

addContainerAttributes(){
  // Not entirely sure what to put here
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 8

添加在运行时动态添加的特定于Angular的标记只会被Angular忽略。[phantomOp]="myItems" [myOper]="oper"仅当编译组件时,Angular才会处理像这样的绑定。通常(使用AoT)是在部署应用程序之前。

如何使用/创建动态模板以使用Angular 2.0编译动态组件?介绍了如何在运行时编译组件。

您可以在组件中引入一个字段

isClicked:boolean = false;
Run Code Online (Sandbox Code Playgroud)

将此静态添加到您的元素

[phantomOp]="isClicked ? myItems : null" [myOper]="isClicked ? oper : null"
Run Code Online (Sandbox Code Playgroud)

在点击处理程序中

(click)="isClicked=true"
Run Code Online (Sandbox Code Playgroud)


Chi*_*hif 5

我最近遇到了类似的情况。我想动态添加和删除captureFileInput 上的属性。现在,只要存在该capture属性,文件输入就会进入捕获模式,因此将值设置为 null 或 '' 对我来说不起作用。

这就是我最终让它发挥作用的方式。我用过@ViewChildElementRef。在你的情况下,它会是这样的:

<div #yourContainer class="container">
  <ul>
    <li> Albums </li>
    <li> Dates </li>
    </ul>
</div>

<button (click)="addContainerAttributes"> Add Container Attributes </button>
Run Code Online (Sandbox Code Playgroud)

然后在TS中

import { Component, ElementRef } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent {
@ViewChild('yourContainer', {static:true}) yourContainer: ElementRef;

....

  addContainerAttributes(){
    // Not entirely sure what to put here
    this.yourContainer.nativeElement.setAttribute('phantomOp', myItems);
    this.yourContainer.nativeElement.setAttribute('myOper', oper);
  }

  // if you wish to completely remove the attribute dynamically
  removeContainerAttributes(){
    this.yourContainer.nativeElement.removeAttribute('phantomOp');
    this.yourContainer.nativeElement.removeAttribute('myOper');
  }
}

Run Code Online (Sandbox Code Playgroud)