programing

자식 구성 요소의 Angular 4 호출 부모 메서드

jooyons 2023. 8. 18. 22:31
반응형

자식 구성 요소의 Angular 4 호출 부모 메서드

Angular 4의 자식 구성 요소에 있는 부모 메서드(deletePhone)를 호출하고 싶습니다.어떻게 하면 제대로 할 수 있을까요?

상위 구성 요소는 다음과 같습니다.

export class ContactInfo implements OnInit {
    phoneForm: FormGroup;
    phones: Phone[];


    constructor(private fb: FormBuilder,
            private userService: UserService) {
    }

    ngOnInit() {
        this.userService.getDataPhones().subscribe(
            phones => {
                this.phones = phones;
            });

        this.phoneForm = this.fb.group({
            phone: ['', [Validators.pattern(PHONE_PATTERN)]]
        });
    }

    deletePhone(phone: Phone) {
        this.userService.deleteUserPhone(phone)
            .subscribe(res => {
                let index = this.phones.indexOf(phone);
                if (index > -1) {
                    this.phones.splice(index, 1);
                }
        });
    }
}
import { Output, EventEmitter } from '@angular/core'; 

...

class ChildComponent {
  @Output() someEvent = new EventEmitter<string>();

  callParent(): void {
    this.someEvent.next('somePhone');
  }
}

ContactInfo의 템플릿

<child-component (someEvent)="deletePhone($event)"

이것은 저에게 효과가 있었습니다(예: 공식 문서).

https://angular.io/api/core/EventEmitter#examples

자식:

@Component({
  selector: 'zippy',
  template: `
  <div class="zippy">
    <div (click)="toggle()">Toggle</div>
    <div [hidden]="!visible">
      <ng-content></ng-content>
    </div>
 </div>`})
export class Zippy {
  visible: boolean = true;
  @Output() open: EventEmitter<any> = new EventEmitter();
  @Output() close: EventEmitter<any> = new EventEmitter();

  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      this.open.emit(null); //emit event here
    } else {
      this.close.emit(null);
    }
  }
}

상위 항목:

<zippy (open)="onOpen($event)" (close)="onClose($event)"></zippy>

저는 @Output()과 같은 상용어구 코드를 좋아하지 않습니다.다른 해결책을 찾았어요. 익명의 함수가 있는 개체를 그냥 전달하세요.

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

@Component({
  selector: 'app-parent',
  styleUrls: ['./parent.component.css'],
  template: `
  <app-child [parentApi]="getParentApi()"></app-child>
`,
})
export class ParentComponent implements OnInit {

  getParentApi(): ParentComponentApi {
    return {
      callParentMethod: (name) => {
        this.parentMethod(name)
      }
    }
  }

  constructor() { }

  ngOnInit() {
  }

  parentMethod(name: string) {
    console.log(`Hello ${name} from parent`)
  }
  
}

export interface ParentComponentApi {
  callParentMethod: (string) => void
}

그리고 아이:

import { Component, OnInit, Input } from '@angular/core';
import { ParentComponentApi } from '../parent/parent.component';

@Component({
  selector: 'app-child',
  template: `<button (click)="callParent()">call parent</button>`,
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  @Input() parentApi: ParentComponentApi

  constructor() { }

  callParent() {
    this.parentApi.callParentMethod("child")
  }

  ngOnInit() {

  }

}

이런 식으로 하는 것이 꽤 안전하다고 생각해요, 안 그래요?

당신이 생각하는 것보다 더 간단합니다.핵심은 부모 메서드를 자식 @Input 속성으로 전달하는 것입니다.온라인으로 테스트합니다.

상위 구성 요소

@Component({
  selector: 'my-app',
  template: `
    <h1>Parent:</h1>
    <p>Parent counting: {{this.count}}</p>

    <child-comp [childInc]="this.inc"></child-comp>
  `
})
export class AppComponent {
  name = "I'm Parent";

  count = 0;

  inc = () => {
    this.count++;
  }
}

하위 구성 요소

@Component({
  selector: 'child-comp',
  template: `
  <h1>Child:</h1> 
  <button (click)="childInc()">Click me!</button>
  `
})
export class ChildComponent  {
  name = "I'm child"

  @Input() childInc: () => void
}

사용한 적이 있습니다.inc = () => {...}권리를 기억할 수 있는 부모의 개념.this를 사용하는 경우inc(){...}개념, 그러면 부모님을 구속해야 합니다.this~하듯이[childInc]="this.inc.bind(this)".

언급URL : https://stackoverflow.com/questions/43323272/angular-4-call-parent-method-in-a-child-component

반응형