Hit*_*lar 5 javascript angular2-directives angular
在我的应用程序中,我将Home作为根组件,另一个名为list的通用组件,我在Home中进行渲染.
我想将数据作为属性传递给我的列表组件,该组件来自XMLHttpRequest.
home.ts
import {Component} from 'angular2/core';
import {DashboardService} from '../../services/dashboard';
import {List} from '../contact/list';
@Component({
selector: 'home',
template:
`
<h3>Home</h3>
<List type="{{type}}"></List>
`
providers: [DashboardService],
directives: [List],
})
export class Home {
private _type: any;
constructor(private _dashboardService: DashboardService) {
this._dashboardService.typeToDisplay()
.subscribe((type) => {
this._type = type;
});
}
}
Run Code Online (Sandbox Code Playgroud)
List.ts
@Component({
selector: 'List',
properties: ['type'],
template: `
<h2>list</h3>
`,
providers: [DashboardService]
})
export class List {
private type: any;
constructor(@Attribute('type') type:string) {
this.type = type;
console.log(type);
}
}
Run Code Online (Sandbox Code Playgroud)
我从typeToDisplay()方法获取字符串数据,它是一个Http请求并分配给类型变量.但当我作为属性传递给列表组件时,我在List构造函数中得到null.
我也尝试了,但我得到"类型"字符串相同的方式.
希望我的问题是明确的.
这种语法
<List type="{{type}}"></List>
Run Code Online (Sandbox Code Playgroud)
正在设置属性而不是属性。
要设置属性,请使用
<List attr.type="{{type}}"></List>
Run Code Online (Sandbox Code Playgroud)
或者
<List [attr.type]="type"></List>
Run Code Online (Sandbox Code Playgroud)
如果您只想List使用可用的值
@Input() type: any;
Run Code Online (Sandbox Code Playgroud)
而不是属性注入。
这样,该值在构造函数中尚不可用,只能在内部ngOnInit()或以后使用。
| 归档时间: |
|
| 查看次数: |
2223 次 |
| 最近记录: |