gpt4 book ai didi

typescript - Angular2 将属性传递给类构造函数

转载 作者:太空狗 更新时间:2023-10-29 17:18:09 24 4
gpt4 key购买 nike

如何在 Angular 2 中将属性从父组件传递到其子组件的类构造函数?

一半的谜团已经解开了,因为属性可以毫无问题地传递给 View 。

/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, View, 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);
}
}

重申一下:

How can I access an attribute inside the child component's class passed in from the parent component?

Repo

最佳答案

已更新至 beta.1

您可以使用 ngOnInit为此

@Component({
selector: 'example',
inputs: ['test', 'hyphenatedTest', '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);
}
}

关于typescript - Angular2 将属性传递给类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31829254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com