programing

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

nasanasas 2020. 11. 26. 08:26
반응형

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


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

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


RxJ를 사용하면 부모 구성 요소에서 Subject를 선언하고이를 자식 구성 요소에 Observable로 전달할 수 있습니다. 자식 구성 요소는이 Observable을 구독하기 만하면됩니다.

상위 구성 요소

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

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

부모 -HTML

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

하위 구성 요소

private eventsSubscription: any

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

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

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

@Input() myInputName: myType

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

예 :

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

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

더 읽어 보려면 :

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


In a parent component you can use @ViewChild() to access child component's method/variable.

@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();
    }
} 

Within the parent, you can reference the child using @ViewChild. When needed (i.e. when the event would be fired), you can just execute a method in the child from the parent using the @ViewChild reference.

참고URL : https://stackoverflow.com/questions/44053227/how-to-emit-an-event-from-parent-to-child

반응형