首页 文章

子组件中的Angular 4调用父方法

提问于
浏览
20

我想在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);
                }
        });
    }
}

3 回答

  • 6
    class ChildComponent {
      @Output() someEvent = new EventEmitter<string>();
    
      callParent() {
        this.someEvent.next('somePhone');
      }
    }
    

    ContactInfo 的模板中

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

    这对我有用(例如来自官方文档):

    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>
    
  • 43

    我不喜欢像@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() {
    
      }
    
    }
    

    我觉得这样做很安全,不是吗?

相关问题