bestsource

부모에서 자녀로 이벤트를 내보내는 방법

bestsource 2023. 3. 25. 11:37
반응형

부모에서 자녀로 이벤트를 내보내는 방법

저는 현재 Angular 2를 사용하고 있습니다.보통 사용하는 것은@Output() addTab = new EventEmitter<any>();그리고 나서.addTab.emit()이벤트를 부모 컴포넌트에 송신합니다.

부모에서 아이로 반대로 우리가 할 수 있는 방법은 없을까?

RxJs 를 사용하면,Subject부모 컴포넌트에 포함시켜 전달한다.Observable하위 구성 요소에 대해 하위 구성 요소가 이 구성 요소에 가입하기만 하면 됩니다.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. 공유 서비스 개념

서비스를 만들고 공유 서비스에서 관찰 가능한 서비스를 사용합니다.자녀가 가입하고 변경 사항이 있을 때마다 자녀에게 알립니다.이것도 인기 있는 방법입니다.입력으로 전달한 데이터 이외의 것을 송신하고 싶은 경우는, 이것을 사용할 수 있습니다.

// SharedService
subject: Subject<Object> = new 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();
    }
} 

업데이트:

각도 8 이상 -

@ViewChild(NumberComponent, { static: false })

부모가 이 입력에 바인드할 수 있도록 하려면 자녀 컴포넌트의 @Input() 데코레이터를 사용합니다.

자 컴포넌트에서는 다음과 같이 선언합니다.

@Input() myInputName: myType

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

예:

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

그러나 개체는 참조로 전달되므로 개체가 자식에서 업데이트되면 상위 개체가 너무 업데이트됩니다.이것은 때때로 원치 않는 행동으로 이어질 수 있습니다.primary 타입에서는 값이 복사됩니다.

자세한 내용은 다음을 참조하십시오.

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

Nested Recursive Child Component가 있었기 때문에 이전 솔루션 중 아무 것도 작동하지 않았습니다.그래서 저는 OnChanges 기능을 사용하여 다음과 같은 방법을 사용했습니다.

상위 컴포넌트

buttonToggle: boolean = false;

buttonClick(): void {
  this.buttonToggle = !this.buttonToggle;
}

상위 HTML

<appNestedChildItemComponent [buttonTrigger]="buttonToggle"></appNestedChildItemComponent>

재귀 중첩된 하위 구성 요소

export class NestedChildItemComponent implements OnInit, OnChanges {

  @Input() buttonTrigger: boolean;
  buttonToggle: boolean = false;

  ngOnInit() {
    this.buttonToggle= buttonToggle;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['buttonTrigger'] && changes['buttonTrigger']?.previousValue != changes['buttonTrigger']?.currentValue) {
      this.buttonToggle= !this.buttonToggle;
      // Do Something triggered by the parent button.
    }
  }
}

부모 내에서 @ViewChild를 사용하여 아이를 참조할 수 있습니다.필요할 때(이벤트가 언제 발생하는지 등) @ViewChild 참조를 사용하여 부모로부터 자녀 내에서 메서드를 실행할 수 있습니다.

같은 개념의 공유 서비스: 로컬 스토어를 자산관리와 함께 사용할 수도 있습니다.부모(들)는 스토어의 상태를 갱신하고 자녀(들)는 스토어 자체에 서브스크립트 할 수 있습니다.

이 접근방식을 사용하면 다대다 이벤트/데이터/정보 전송이 쉬워지며 첫 번째 질문을 적용할 수 있습니다.

단점: 더 무거운 장점: 더 강력한 대규모 애플리케이션 진화

추천할 만한 매장 관리 라이브러리의 예: https://github.com/ngneat/elf

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

반응형