Angular 2-在父组件上单击按钮时,将数据从父组件传递到子组件

时间:2018-07-17 08:28:44

标签: angular components

在parentComponenet.html

</div><button(click)="discoverClicked()">Discover</button></div>
<child-component></child-component>

在parentComponent.ts

export class parentComponent implements OnInit {
    discoverClicked(){
       //send data to childComponent
    }
}

在childComponent.ts

export class childComponent implements OnInit {
    discoverClicked(){
       //received data from parent component
    }
}

是否有上述方法?

2 个答案:

答案 0 :(得分:6)

根据您的数据,一种方法是引入一些变量,例如在父组件中:

@Component(...)
export class ParentComponent {
    private data: any;

    discoverClicked(){
        // do the thing
        this.data = "some data not matter how you got it";
    }
}

parent-component.html中:

</div><button(click)="discoverClicked()">Discover</button></div>
<child-component [data]=data></child-component>

然后添加子组件:

@Component(...)
export class ChildComponent {

    @Input('data')
    set data(data: any) {
        //do whatever you want with your data here, this data will be passed from parent component
    }
}

如果您需要更复杂的行为,则可以提供一些服务,该服务将为您保存数据,然后将其传递给子组件,例如:

@Injectable()
export class DataService {
    private _data: BehaviorSubject<any> = new BehaviorSubject<any>(null);

    public setData(data: any){
        this._data.next(data);
    }

    public getData(): Observable<any> {
        return this._data.asObservable();
    }
}

然后在父组件中:

@Component(...)
export class ParentComponent {

    constructor(private dataService: DataService){}

    discoverClicked(){
        // do the thing
        this.dataService.setData("any data that you want");
    }
}

在子组件中:

@Component(...)
export class ChilComponent{

    constructor(private dataService: DataService){
        this.dataService.getData().subscribe(data=>{
            // Do whatever you want with your data
        }
    }

}

P.S。 不要忘记在某处提供服务并取消订阅子组件中的数据。

答案 1 :(得分:0)

添加此内容,在您的父HTML标记中添加let-c =“ close” let-d =“ dismiss”。 然后单击按钮,将“ d”作为参数传递。并在ts文件中,每当您要关闭NgbModal时,请听参数并调用函数d()