父组件的角度5设置子组件属性

时间:2018-12-04 07:03:44

标签: angular

我想从父组件设置子组件属性

parent.component.html

<div>
<child-detail #myCarousel [childList]="detail.List" ></child-detail>
</div>  

parent.component.ts

@Component({
  selector: "parent",
  templateUrl: "./parent.component.html",
 })  
export class AppComponent { 
  public detail; // it is of JSON type
}

child.component.ts

@component({
 selector:'child-detail',
 templateUrl: './child.component.html'
})
export class ChildDetailComponent{
  @Input() public childList;   // that list of array type
}

child.component.html

<div *ngFor = "let list of childList">
 <li>{{list}} </li>
</div>

我知道我可以通过@Input()绑定来设置此属性,但这只能在组件初始化时设置,我想在某个时候以编程方式在中间设置它。

我知道我可以使用

在父级中访问此子级属性
@ViewChild(ChildDetailComponent) childDetailComponent: ChildDetailComponent;
console.log(this.childDetailComponent.childList);

但是我想以编程方式在父项的任何情况下进行设置。

3 个答案:

答案 0 :(得分:1)

我不确定在不使用@Input属性的情况下如何做。

只要您传递给它的输入发生变化,它也会反映在子组件中。您可以在子组件的ngOnChanges中对其进行跟踪。只需尝试log切换到console

尝试一下:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  detail: any = {
    childList: []
  };

  setChildList() {
    this.detail.childList = [
      { id: 1, name: 'John' },
      ...
    ];
  }

}

在模板中:

<button (click)="setChildList()">Set Child List</button>
<hello [childList]="detail.childList"></hello>

在此@Input属性在“单击按钮”上更改。但就您而言,您可以简单地将setChildList方法称为事件。


这是您推荐的Working Sample StackBlitz

答案 1 :(得分:0)

在子组件中使用@input。可以使用ngOnChanges收听子组件中的更改。

@Input() name: string;

ngOnChanges(changes: SimpleChanges) {
  const name: SimpleChange = changes.name;
  console.log('prev value: ', name.previousValue);
  console.log('got name: ', name.currentValue);
}

工作stackblitz

答案 2 :(得分:0)

您可以使用服务实用地共享数据。

步骤1 :创建数据共享服务。

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

} 

第2步:更改消息

export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
   this.data.changeMessage("Hello from Sibling")
  }

第3步:获取消息

export class ChildComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}
相关问题