Jon*_*les 234 javascript angular
如何有条件地添加元素属性,例如checked复选框?
以前版本的Angular已经NgAttr和我认为NgChecked哪些似乎都提供了我所追求的功能.但是,Angular 2中似乎不存在这些属性,我看不到提供此功能的其他方法.
Gün*_*uer 497
null 删除它:
[attr.checked]="value ? '' : null"
Run Code Online (Sandbox Code Playgroud)
要么
[attr.checked]="value ? 'checked' : null"
Run Code Online (Sandbox Code Playgroud)
Sha*_*Roy 33
在angular-2属性语法中
<div [attr.role]="myAriaRole">
Run Code Online (Sandbox Code Playgroud)
将属性角色绑定到表达式myAriaRole的结果.
所以可以使用像
[attr.role]="myAriaRole ? true: null"
Run Code Online (Sandbox Code Playgroud)
小智 14
精炼GünterZöchbauer答案:
现在这似乎有所不同.我试图这样做有条件地将href属性应用于锚标记.您必须对"不适用"案例使用undefined.作为一个例子,我将演示一个有条件地应用了href属性的链接.
根据超链接规范,没有href属性的锚标记将变为纯文本,表示链接的占位符.
对于我的导航,我有一个链接列表,但其中一个链接代表当前页面.我不希望当前页面链接成为链接,但仍希望它出现在列表中(它有一些自定义样式,但此示例已简化).
<a [attr.href]="currentUrl !== link.url ? link.url : undefined">
Run Code Online (Sandbox Code Playgroud)
我认为这比在span和anchor标签上使用两个*ngIf更干净.
Qwe*_*tiy 13
如果您确实需要checked,最好使用 property 而不是 attribute 并为其分配一些布尔值:
<input type="checkbox" [checked]="smth">
Run Code Online (Sandbox Code Playgroud)
如果你想有条件地添加任意属性,你可以使用绑定到它:
<p [attr.data-smth]="smth">
Run Code Online (Sandbox Code Playgroud)
undefined或null则不添加属性。当然,您attr.checked也可以使用它:
<input type="checkbox" [attr.checked]="smth ? '' : null">
Run Code Online (Sandbox Code Playgroud)
但请注意,在这种情况下 attr 与被检查不同步,因此以下组合
<input type="checkbox" [checked]="false" [attr.checked]="''">
Run Code Online (Sandbox Code Playgroud)
将导致带有checked属性的复选框未选中。
以及一个完整的例子:
import { Component } from "@angular/core";
@Component({
selector: "app-root",
template: `
<p [attr.data-smth]="e">The value is: {{what(e)}}</p>
<p [attr.data-smth]="s">The value is: {{what(s)}}</p>
<p [attr.data-smth]="u">The value is: {{what(u)}}</p>
<p [attr.data-smth]="n">The value is: {{what(n)}}</p>
<p [attr.data-smth]="t">The value is: {{what(t)}}</p>
<p [attr.data-smth]="f">The value is: {{what(f)}}</p>
<input type="checkbox" [checked]="t">
<input type="checkbox" [checked]="f">
<input type="checkbox" [attr.checked]="t ? '' : null">
<input type="checkbox" [attr.checked]="f ? '' : null">
<input type="checkbox" [checked]="false" [attr.checked]="''">
`,
styles: [`
p[data-smth] {
color: blue;
}
`]
})
export class AppComponent {
e = ""
s = "abc"
u = undefined
n = null
t = true
f = false
what(x) {
return typeof x === 'string' ? JSON.stringify(x) : x + ""
}
}
Run Code Online (Sandbox Code Playgroud)
这就是结果:
和标记:
小智 8
如果它是一个输入元素,您可以编写类似....
<input type="radio" [checked]="condition">的内容。条件的值必须为真或假。
同样对于样式属性...
<h4 [style.color]="'red'">Some text</h4>
| 归档时间: |
|
| 查看次数: |
160819 次 |
| 最近记录: |