gpt4 book ai didi

custom-component - 如何将 super 组件类变量访问到子组件类中?

转载 作者:行者123 更新时间:2023-12-05 04:15:05 26 4
gpt4 key购买 nike

我如何在 Angular2 中将 super 组件类变量访问到子组件中?

super 组件Article.ts

@Component({
selector: 'article'
})

@View({
templateUrl: './components/article/article.html?v=<%= VERSION %>',
styleUrls : ['./components/article/article.css'],
directives: [CORE_DIRECTIVES, AmCard, NgFor]
})

export class Article{

articleArr : Array;
constructor() {
this.articleArr = new Array();
}

articleSubmit(articleSubject, articleName, articleUrl)
{
this.articleArr.push({title: articleSubject.value, user : articleName.value, url : articleUrl.value});

}
}

super 组件article.html

<div *ng-for="#item of articleArr">
<am-card card-title="{{item.title}}" card-link="{{item.url}}" card-author="{{item.user}}"></am-card>
</div>

子组件 amcard.ts

@Component({
selector: 'am-card',
properties : ['cardTitle', 'cardLink', 'cardAuthor']
})

@View({
templateUrl: './components/card/card.html?v=<%= VERSION %>',
styleUrls : ['./components/card/card.css'],
directives: [CORE_DIRECTIVES]
})

export class AmCard {
constructor() {

}
}

子组件 amcard.html

<div class="card">
...
</div>

所以我的问题是如何访问AmCard类中的文章类的articleArr

进阶 谢谢你帮助我。

最佳答案

您可以使用 angular2 依赖注入(inject)将父组件注入(inject)子组件。使用 @Inject参数装饰器和 forwardRef这样做(forwardRef 允许我们引用尚未定义的 Article)。所以你的 AmCard 组件看起来像(见 this plunker ):

@Component({
selector: 'am-card',
template: `
<span>{{ articleLength }} - {{ cardTitle }}<span>
`
})
export class AmCard {
@Input() cardTitle: string;
@Input() cardLink: string;
@Input() cardAuthor: string;

constructor(@Inject(forwardRef(() => Article)) article: Article) {
// here you have the parent element - `article`
// you can do whatever you want with it
this.articleLength = article.articleArr.length;
setTimeout(() => {
article.articleSubmit({ value: Math.random() }, {}, {});
}, 1000)
}
}

但是,恕我直言,这是一个糟糕的模式。如果可能的话,最好使用output property (event binding)将消息传递给父组件,并在父组件中处理该消息。在你的情况下它看起来像(见 this plunker ):

@Component({ /* ... component config */})
class AmCard {
// ... input properties
@Output() callSubmit = new EventEmitter();

constructor() {
setTimeout(() => {
// send message to a parent component (Article)
this.callSubmit.next({ value: Math.random() });
}, 1000)
}
}

@Component({
// ... component config
template: `
<h3>Article array:</h3>
<div *ng-for="#item of articleArr">
<am-card
[card-title]="item.title"
[card-link]="item.url"
[card-author]="item.user"
`/* handle message from AmCard component */+`
(call-submit)=" articleSubmit($event, {}, {}) "
></am-card>
</div>
`
})
class Article{
// ... properties and constructor

articleSubmit(aa, an, au) {
this.articleArr.push({ title: as.value, user: an.value, url: au.value });
}
}

关于custom-component - 如何将 super 组件类变量访问到子组件类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33422030/

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