[angular] 부모에서 자식으로 이벤트를 내보내는 방법은 무엇입니까?

저는 현재 Angular 2를 사용 @Output() addTab = new EventEmitter<any>();하고 있습니다. 일반적으로 우리는 addTab.emit()부모 구성 요소에 이벤트를 내 보냅니다.

부모에서 자식으로 반대로 할 수있는 방법이 있습니까?



답변

RxJs를 사용하면 Subject부모 구성 요소에서를 선언하고 Observable자식 구성 요소 로 전달할 수 있으며 자식 구성 요소는 this Observable.

상위 구성 요소

eventsSubject: Subject<void> = new Subject<void>();

emitEventToChild() {
  this.eventsSubject.next();
}

부모 -HTML

<child [events]="eventsSubject.asObservable()"> </child>    

하위 구성 요소

private eventsSubscription: Subscription;

@Input() events: Observable<void>;

ngOnInit(){
  this.eventsSubscription = this.events.subscribe(() => doSomething());
}

ngOnDestroy() {
  this.eventsSubscription.unsubscribe();
}


답변

내가 아는 한, 그렇게 할 수있는 두 가지 표준 방법이 있습니다.

1. @ 입력

부모의 데이터가 변경 될 때마다 자식은 ngOnChanges 메서드에서 이에 대한 알림을받습니다. 아이는 그것에 대해 행동 할 수 있습니다. 이것은 아이와 상호 작용하는 표준 방법입니다.

Parent-Component
public inputToChild: Object;

Parent-HTML
<child [data]="inputToChild"> </child>

Child-Component: @Input() data;

ngOnChanges(changes: { [property: string]: SimpleChange }){
   // Extract changes to the input property by its name
   let change: SimpleChange = changes['data'];
// Whenever the data in the parent changes, this method gets triggered. You 
// can act on the changes here. You will have both the previous value and the 
// current value here.
}
  1. 공유 서비스 개념

서비스를 만들고 공유 서비스에서 Observable을 사용합니다. 자녀가이를 구독하고 변경 사항이있을 때마다 자녀에게 알림이 전송됩니다. 이것은 또한 널리 사용되는 방법입니다. 입력으로 전달한 데이터 이외의 것을 보내려는 경우이를 사용할 수 있습니다.

SharedService
subject: Subject<Object>;

Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);

Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{

// Whenever the parent emits using the next method, you can receive the data 
in here and act on it.})


답변

부모 구성 요소에서 @ViewChild ()를 사용하여 자식 구성 요소의 메서드 / 변수에 액세스 할 수 있습니다.

@Component({
  selector: 'app-number-parent',
  templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
    @ViewChild(NumberComponent)
    private numberComponent: NumberComponent;
    increase() {
       this.numberComponent.increaseByOne();
    }
    decrease() {
       this.numberComponent.decreaseByOne();
    }
} 

최신 정보:

Angular 8 이상-

@ViewChild(NumberComponent, { static: false })


답변

부모가이 입력에 바인딩 할 수 있도록 자식 구성 요소에서 @Input () 데코레이터를 사용합니다.

자식 구성 요소에서 그대로 선언합니다.

@Input() myInputName: myType

부모에서 자식으로 속성을 바인딩하려면 바인딩 괄호와 그 사이에 입력 이름을 템플릿에 추가해야합니다.

예 :

<my-child-component [myChildInputName]="myParentVar"></my-child-component>

그러나 객체는 참조로 전달되므로 객체가 자식에서 업데이트되면 부모의 var가 너무 업데이트됩니다. 이로 인해 언젠가 원치 않는 동작이 발생할 수 있습니다. 기본 유형을 사용하면 값이 복사됩니다.

더 읽어 보려면 :

문서 : https://angular.io/docs/ts/latest/cookbook/component-communication.html


답변

부모 내에서 @ViewChild를 사용하여 자식을 참조 할 수 있습니다. 필요한 경우 (즉, 이벤트가 시작될 때) @ViewChild 참조를 사용하여 부모의 자식에서 메서드를 실행할 수 있습니다.


답변