Javascript 如何在 Angular 2 中添加条件属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36745734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:30:53  来源:igfitidea点击:

How to add conditional attribute in Angular 2?

javascriptangular

提问by Jonathan Miles

How can I conditionally add an element attribute e.g. the checkedof a checkbox?

如何有条件地添加元素属性,例如checked复选框的?

Previous versions of Angular had NgAttrand I think NgCheckedwhich all seem to provide the functionality that I'm after. However, these attributes do not appear to exist in Angular 2 and I see no other way of providing this functionality.

以前版本的 Angular 有NgAttr并且我认为NgChecked它们似乎都提供了我所追求的功能。但是,这些属性在 Angular 2 中似乎不存在,我认为没有其他方法可以提供此功能。

回答by Günter Z?chbauer

nullremoves it:

null删除它:

[attr.checked]="value ? '' : null"

or

或者

[attr.checked]="value ? 'checked' : null"

Hint:

暗示:

Attribute vs property

属性 vs 属性

When the HTML element where you add this binding does not have a property with the name used in the binding (checkedin this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;, then [xxx]="..."can not be used.

如果添加此绑定的 HTML 元素没有绑定中使用的名称的属性(checked在这种情况下),并且没有 Angular 组件或指令应用于具有 的同一元素@Input() checked;,则[xxx]="..."不能使用。

See also What is the difference between properties and attributes in HTML?

另请参阅HTML 中的属性和属性之间有什么区别?

What to bind to when there is no such property

没有这样的属性时绑定什么

Alternatives are [style.xxx]="...", [attr.xxx]="...", [class.xxx]="..."depending on what you try to accomplish.

替代方案是[style.xxx]="..."[attr.xxx]="..."[class.xxx]="..."取决于您尝试完成的任务。

Because <input>only has a checkedattribute, but no checkedproperty [attr.checked]="..."is the right way for this specific case.

因为<input>只有一个checked属性,但没有checked属性[attr.checked]="..."是这种特定情况的正确方法。

Attributes can only handle string values

属性只能处理字符串值

A common pitfall is also that for [attr.xxx]="..."bindings the value (...) is alwaysstringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

一个常见的缺陷还在于,对于[attr.xxx]="..."绑定,值 ( ...)始终是字符串化的。只有属性和@Input()s 可以接收其他值类型,如布尔值、数字、对象、...

Mostproperties and attributes of elements are connected and have the same name.

元素的大多数属性和属性是相连的并且具有相同的名称。

Property-attribute connection

属性-属性连接

When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.

当绑定到属性时,该属性也只从属性接收字符串化的值。
当绑定到属性时,属性会收到绑定到它的值(布尔值、数字、对象等),而属性又是字符串化的值。

Two cases where attribute and property names do not match.

属性和属性名称不匹配的两种情况。

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]="even though no such property exists (same for colspan)

从那时起,Angular 发生了变化,并且知道这些特殊情况并处理它们,以便您可以绑定到<label [for]="即使不存在此类属性(与 相同colspan

回答by Shaishab Roy

in angular-2 attribute syntax is

在 angular-2 属性语法中是

<div [attr.role]="myAriaRole">

Binds attribute role to the result of expression myAriaRole.

将属性角色绑定到表达式 myAriaRole 的结果。

so can use like

所以可以使用像

[attr.role]="myAriaRole ? true: null"

回答by Ragnaraxis

Refining Günter Z?chbauer answer:

精炼 Günter Z?chbauer 回答:

This appears to be different now. I was trying to do this to conditionally apply an href attribute to an anchor tag. You must use undefined for the 'do not apply' case. As an example, I'll demonstrate with a link conditionally having an href attribute applied.

这现在似乎不同了。我试图这样做是为了有条件地将 href 属性应用于锚标记。对于“不适用”的情况,您必须使用 undefined。作为示例,我将使用一个有条件地应用了 href 属性的链接进行演示。

An anchor tag without an href attribute becomes plain text, indicating a placeholder for a link, per the hyperlink spec.

根据超链接规范,没有 href 属性的锚标记变为纯文本,指示链接的占位符。

For my navigation, I have a list of links, but one of those links represents the current page. I didn't want the current page link to be a link, but still want it to appear in the list (it has some custom styles, but this example is simplified).

对于我的导航,我有一个链接列表,但其中一个链接代表当前页面。我不希望当前页面链接是一个链接,但仍然希望它出现在列表中(它有一些自定义样式,但这个例子是简化的)。

<a [attr.href]="currentUrl !== link.url ? link.url : undefined">

This is cleaner than using two *ngIf's on a span and anchor tag, I think.

我认为这比在跨度和锚标记上使用两个 *ngIf 更干净。

回答by WapShivam

you can use this.

你可以用这个。

<span [attr.checked]="val? true : false"> </span>

<span [attr.checked]="val? true : false"> </span>

回答by Rohit Tirmanwar

If it's an input element you can write something like.... <input type="radio" [checked]="condition">The value of condition must be true or false.

如果它是一个输入元素,您可以编写类似... <input type="radio" [checked]="condition">的内容。条件的值必须为真或假。

Also for style attributes... <h4 [style.color]="'red'">Some text</h4>

同样对于样式属性... <h4 [style.color]="'red'">Some text</h4>

回答by Jo?o Ghignatti

You can use a better approach for someone writing HTML for an already existing scss.
html

对于为已经存在的 scss 编写 HTML 的人,您可以使用更好的方法。
html

[attr.role]="<boolean>"

scss

scss

[role = "true"] { ... }

That way you don't need to <boolean> ? true : nullevery time.

这样你就不需要<boolean> ? true : null每次都这样了。

回答by Aishwarya Kathavarayan

Here, the paragraph is printed only 'isValid' is true / it contains any value

此处,该段落仅打印 'isValid' 为真/它包含任何值

<p *ngIf="isValid ? true : false">Paragraph</p>

回答by Cody

Inline-Maps are handy, too.

内联地图也很方便。

They're a little more explicit & readable as well.

它们也更加明确和可读。

[class]="{ 'true': 'active', 'false': 'inactive', 'true&false': 'some-other-class' }[ trinaryBoolean ]"

Just another way of accomplishing the same thing, in case you don't like the ternary syntax or ngIfs (etc).

这是完成相同事情的另一种方式,以防您不喜欢三元语法或ngIfs (等)。