Pab*_*blo 46 javascript angular
我正在学习Angular2.我有一个带有变量的组件,它是一个对象.我正在迭代对象的字段,并根据该位置的数据类型,我需要渲染一个不同的组件.在这种情况下,我想要tu渲染,label如果typeof那个位置是一个number如何这不起作用
<div>
<div *ngIf='obj'>
<label *ngFor="let key of keys; let i = index">
<label class='key'>{{key}}:</label>
<label class='number' *ngIf='typeof obj[key] === "number"'>
<!-- label class='number' *ngIf='obj[key] | typeof === "number"' -->
{{ obj[key] }}
</label>
</label>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
我还创建了一个管道,以便在typeof打印值时使用哪个,但不在*ngIf中
Gün*_*uer 74
模板中不提供诸如window,typeof枚举或静态方法之类的全局变量.只有组件类和打字稿语言结构的成员可用.
您可以为组件添加辅助方法,例如
isNumber(val) { return typeof val === 'number'; }
Run Code Online (Sandbox Code Playgroud)
并使用它
<label class='number' *ngIf='isNumber(obj[key])'>
Run Code Online (Sandbox Code Playgroud)
Arm*_*yan 32
您可以创建简单的管道,它将接收当前项目并返回项目类型。
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'typeof'
})
export class TypeofPipe implements PipeTransform {
transform(value: any): any {
console.log("Pipe works ", typeof value);
return typeof value;
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以typeof像这样在 html 中使用管道
*ngIf = (item | typeof) === 'number'
Run Code Online (Sandbox Code Playgroud)
如上所述,在 html 中使用函数调用时要小心。它更喜欢使用管道而不是函数调用。这是Stackblitz示例。在第一种情况下,任何更改检测都会触发函数调用(例如:单击按钮)。
zur*_*fyx 12
或者,您可以比较构造函数名称.
{{ foo.constructor.name === 'FooClass' }}
Run Code Online (Sandbox Code Playgroud)
这里的详细信息.
小智 8
我刚刚试过这个,发现它在生产中不起作用,因为函数名称被缩短了。使用类似的东西更安全:
foo instanceof FooClass
Run Code Online (Sandbox Code Playgroud)
但请注意,您必须在组件/指令中执行此操作,因为instanceOf在模板中不可用:
// In your component
isFoo(candidate){
return candidate instanceof FooClass;
}
// in your template
{{isFoo(maybeFoo)}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58837 次 |
| 最近记录: |