简体   繁体   English

在html模板angular 2中动态设置组件的属性

[英]Dynamically set attribute on component in html template angular 2

I am trying to set an attribute on a component if a certain expression is true. 如果某个表达式为true,我试图在组件上设置属性。 Could someone give me an example? 有人能举个例子吗?

What I have now: 我现在拥有的:

 <div [danger]="inArray(choice.likers, user, id)"></div>

but this does not compile. 但这不编译。

inArray is my own method which returns true or false. inArray是我自己的方法,返回true或false。 What I would like to see is, if the expression returns true, the output will be 我想看到的是,如果表达式返回true,则输出将为

<div danger></div>

In angular 1 there was this: ng-attr-... statement that did exactly the above. 在角度1中有这样的:ng-attr -...声明完全如上所述。

To set an attribute use attribute binding : 要设置属性使用属性绑定

 <div [attr.danger]="inArray(choice.likers, user, id)"></div>

If you want to show a empty attribute conditionally return empty string or null in inArray() : 如果要显示空属性,请在inArray()有条件地返回空字符串或null:

inArray() {
    let value;
    if (isInArray) {
      value = '';
    } else {
      value = null;
    }
    return value;
  }

so the attribute will empty or the danger attribute dont exist. 所以该属性将为空或危险属性不存在。 The result is: 结果是:

<div danger></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 HTML5 数据属性中设置 angular 组件变量值 - set angular component variable value in an HTML5 data attribute Angular在属性html中不起作用 - Angular not working inside attribute html 在 Angular 组件的模板中使用“this”关键字 - Using 'this' keyword in Angular component's template 我可以使用角度组件选择器作为该组件的属性吗? - Can I use an angular component selector as an attribute for that component? Angular 2将数据从组件B传递到组件B定义的模板 - Angular 2 Pass Data from Component B to the template defined by Component B 无法绑定到Angular组件的Bootstrap模态中动态添加的输入 - Can't bind to dynamically added input in Bootstrap modal of Angular component 从@Component Angular 2更新@ Directive模板选择器中绑定的数据 - Updating data bound in @Directive's template selector from @Component Angular 2 Angular 2:在组件本身内部动态创建时如何使用传递给组件的数据 - Angular 2: how to use the data passed to component when dynamically created inside component itself 为什么 angular 中的输入属性没有采用我通过 html 文件发送的值? - why Input attribute in angular is not taking the value that I sent by the html file? Angular 2如何使用我在html中的组件中获得的数据 - Angular 2 How to use data I got in the html in component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM