typescript – Angular2将属性传递给类构造函数
发布时间:2020-12-17 07:17:13 所属栏目:安全 来源:网络整理
导读:如何将属性从父组件传递到Angular 2中的子组件的类构造函数? 计算出一半的神秘感,因为属性可以毫无问题地传递给视图. /client/app.ts import {Component,View,bootstrap} from 'angular2/angular2';import {Example} from 'client/example';@Component({ se
如何将属性从父组件传递到Angular 2中的子组件的类构造函数?
计算出一半的神秘感,因为属性可以毫无问题地传递给视图. /client/app.ts import {Component,View,bootstrap} from 'angular2/angular2'; import {Example} from 'client/example'; @Component({ selector: 'app' }) @View({ template: `<p>Hello</p> <example [test]="someAttr" [hyphenated-test]="someHyphenatedAttr" [alias-test]="someAlias"></example> `,directives: [Example] }) class App { constructor() { this.someAttr = "attribute passsed to component"; this.someHyphenatedAttr = "hyphenated attribute passed to component"; this.someAlias = "attribute passed to component then aliased"; } } bootstrap(App); /client/example.ts import {Component,Attribute} from 'angular2/angular2'; @Component({ selector: 'example',properties: ['test','hyphenatedTest','alias: aliasTest'] }) @View({ template: ` <p>Test: {{test}}</p> <!-- result: attribute passsed to component --> <p>Hyphenated: {{hyphenatedTest}}</p> <!-- result: hyphenated attribute passed to component --> <p>Aliased: {{alias}}</p> <!-- result: attribute passed to component then aliased --> <button (click)="attributeCheck()">What is the value of 'this.test'?</button> <!-- result: attribute passed to component --> ` }) /******************************************************************* * HERE IS THE PROBLEM. How to access the attribute inside the class? *******************************************************************/ export class Example { constructor(@Attribute('test') test:string) { console.log(this.test); // result: undefined console.log(test); // result: null } attributeCheck() { alert(this.test); } } 要重新迭代:
Repo
已更新至beta.1
您可以使用ngOnInit @Component({ selector: 'example',inputs: ['test','alias: aliasTest'],template: ` <p>Test: {{test}}</p> <!-- result: attribute passsed to component --> <p>Hyphenated: {{hyphenatedTest}}</p> <!-- result: hyphenated attribute passed to component --> <p>Aliased: {{alias}}</p> <!-- result: attribute passed to component then aliased --> <button (click)="attributeCheck()">What is the value of 'this.test'?</button> <!-- result: attribute passed to component --> ` }) export class Example { ngOnInit() { console.log(this.test); this.attributeCheck(); } attributeCheck() { alert(this.test); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |