加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:06:58 所属栏目:安全 来源:网络整理
导读:在parentComponenet.html /divbutton(click)="discoverClicked()"Discover/button/divchild-component/child-component 在parentComponent.ts export class parentComponent implements OnInit { discoverClicked(){ //send data to childComponent }} 在chi
在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
    }
}

有没有办法如上所述?

解决方法

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

@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
        }
    }

}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读