Angular 2 - 获取组件实例

问题描述 投票:0回答:2

我有两个这样的组件:

@Component({
    selector: 'comp1',
    template: `<h1>{{ custom_text }}</h2>`
})
export class Comp1 {
    custom_text:string;
    constructor(text:string) {
        this.custom_text = text;
    }
}

/*********************************************/

@Component({
    selector: 'comp2',
    directives: [Comp1],
    template: `
    <b>Comp 2</b>
    <comp1></comp1>
    `
})
export class Comp2 {
    constructor() {
        // ...
        // How to send my own text to comp1 from comp2
        // ...
    }
}

是否可以将我自己的文本从

comp1
发送到
comp2

是否可以从

comp1
获取
comp2
实例?

typescript angular angular2-template
2个回答
5
投票

comp2 是 comp1 的父级,所以

  • 要将数据从子级发送到父级(comp1 到 comp2),请向子级添加 OutputProperty
    @Output() someEvent = newEventEmitter();

    emit()
    其上的事件:
    this.someEvent.emit('some text');

    父级需要绑定到输出属性/活动:
    <comp2 (someEvent)="someHandler()"></comp2>
  • 要获取对子组件实例的引用(comp2 获取对 comp1 的引用),请在 comp2 中使用
    @ViewChild
    @Query
    @ViewChild(Comp1) viewChild:comp1;
    然后,您可以在
    this.comp1
    中访问
    ngAfterViewInit()
    ,或在组件生命周期的后期。

1
投票

是的,这很容易实现,

查看教程:多个组件 Angular2 教程的第 3 部分了解如何发送输入。

@Component({
    selector: 'comp1',
    template: `<h1>{{customText}}</h2>`,
    inputs: ['customText']
})
export class Comp1 {
    public customText:string;
    constructor(text:string) {
        this.customText= text;
    }

 // ngOnChange to make sure the component is in sync with inputs changes in parent
 ngOnChanges() {
       this.customText= text;
    }
}

/*********************************************/

@Component({
    selector: 'comp2',
    directives: [Comp1],
    template: `
    <b>Comp 2</b>
    <comp1 customText = "My Custom Test"></comp1>
    `
})
export class Comp2 {
    constructor() {
    }
}

尝试一下,让我知道效果如何。

© www.soinside.com 2019 - 2024. All rights reserved.