programing

자녀가 Angular 2에서 부모 이벤트를 수신합니다.

bestprogram 2023. 7. 31. 21:34

자녀가 Angular 2에서 부모 이벤트를 수신합니다.

각진 문서에는 부모로부터 자녀 이벤트를 듣는 것에 대한 주제가 있습니다.괜찮아요.하지만 내 목적은 반대야!내 앱에는 관리 페이지의 레이아웃 보기(사이드바 메뉴, 작업 표시줄, 상태 등)를 유지하는 'admin.component'가 있습니다.이 상위 구성요소에서 나는 관리자의 다른 페이지 간에 기본 보기를 변경하도록 라우터 시스템을 구성했습니다.문제는 변경 후 저장하는 것이고, 사용자는 작업 표시줄(admin.component에 배치됨)에서 저장 버튼을 클릭하고 하위 구성 요소는 직원 저장을 위해 해당 클릭 이벤트를 들어야 합니다.

후세를 위해 좀 더 전통적인 해결책을 언급하고 싶습니다. ViewChild에 대한 참조를 얻은 다음 방법 중 하나를 직접 호출하면 됩니다.

@Component({
  selector: 'app-child'
})
export class ChildComponent {

  notifyMe() {
    console.log('Event Fired');
  }
}

@Component({
  selector: 'app-parent',
  template: `<app-child #child></app-child>`
})
export class ParentComponent {

  @ViewChild('child')
  private child: ChildComponent;

  ngOnInit() {
    this.child.notifyMe();
  }
}

이 문서가 귀하에게 도움이 될 수 있다고 생각합니다.

실제로 부모가 자녀에게 제공하는 관찰 가능한/주제를 활용할 수 있습니다.그런 것들:

@Component({
  (...)
  template: `
    <child [parentSubject]="parentSubject"></child>
  `,
  directives: [ ChildComponent ]
})
export class ParentComponent {
  parentSubject:Subject<any> = new Subject();

  notifyChildren() {
    this.parentSubject.next('some value');
  }
}

하위 구성 요소는 다음 주제에 대해 간단히 구독할 수 있습니다.

@Component({
  (...)
})
export class ChildComponent {
  @Input()
  parentSubject:Subject<any>;

  ngOnInit() {
    this.parentSubject.subscribe(event => {
      // called when the notifyChildren method is
      // called in the parent component
    });
  }

  ngOnDestroy() {
    // needed if child gets re-created (eg on some model changes)
    // note that subsequent subscriptions on the same subject will fail
    // so the parent has to re-create parentSubject on changes
    this.parentSubject.unsubscribe();
  }

}

그렇지 않으면 유사한 방식으로 이러한 주제를 포함하는 공유 서비스를 활용할 수 있습니다.

만약 제가 질문을 올바르게 이해한다면 여기서 더 노골적인 접근이 가능할지도 모릅니다.가정 --

  • OP의 상위 구성 요소에 저장 버튼이 있습니다.
  • 저장해야 하는 데이터가 하위 구성 요소에 있습니다.
  • 하위 구성 요소에 필요한 다른 모든 데이터는 서비스에서 액세스할 수 있습니다.

상위 구성 요소

<button type="button" (click)="prop1=!prop1">Save Button</button>
<app-child-component [setProp]='prop1'></app-child-component>

그리고 아이 안에서..

prop1:boolean;
  @Input()
  set setProp(p: boolean) {
    // -- perform save function here
}

이렇게 하면 버튼 클릭이 하위 구성 요소로 전송됩니다.여기서 자식 구성 요소는 데이터를 독립적으로 저장할 수 있습니다.

편집: 상위 템플릿의 데이터도 버튼 클릭과 함께 전달해야 하는 경우 이 방법으로도 가능합니다.그렇다면 알려주시면 코드 샘플을 업데이트하겠습니다.

받으시는 분들을 위해서.Cannot read property 'notifyMe' of undefined

내부 메소드 호출 시도ngAfterViewInit()대신에ngOnInit()

언급URL : https://stackoverflow.com/questions/37677122/child-listens-for-parent-event-in-angular-2