0

에서 함수/변수에 액세스 할 수 있습니다.Angular2 내가 자식 클래스에 부모 클래스의 메소드에 액세스하려는 다른 클래스

내 부모 클래스는

export class Parent{ 
    constructor() {} 
    present() { 
    } 
} 

하고 내 아이 클래스입니다 : 내가 자식 클래스에서 부모 클래스부터 현재() 메서드를 호출 할

export class Child { 
    constructor() {} 
    submit(){ 
     this.toast.present(); 
    } 
} 

.

+0

:

코드는 아래에 첨부? 부모는 자녀가 누구인지를 알고 있습니까? –

+0

당신은 [링크]를 확인 했 (https://plnkr.co/edit/Qw11UOP5WxEdwRXZYfo4?p=preview)? –

+0

코드에 따라 Child의 메서드에서 부모의 present() 메서드에 액세스하려고합니다. 그렇지? 그리고 ChildComponent가 예제에서 ParentComponent에 있다고 가정합니다. –

답변

0

당신은 당신은 @Output 데코레이터를 사용하여 이벤트를 방출 할 수 아이

class Parent{ 
    constructor() {} 
    present() { 
     console.log("I am from parent") 
    } 
} 

class Child extends Parent{ 
    constructor() { 
     super(); 
    } 

    submit(){ 
     super.present(); 
    } 
} 

let x = new Child(); 
x.submit(); 
0

에서 부모의 메소드를 호출 super 키워드를 사용할 수 있습니다.

자녀의 구성 요소가 있어야한다 :

import { Component, Input, Output, EventEmitter } from '@angular/core'; 
@Component({ 
selector: 'child', 
templateUrl: 'child.html', 
}) 

export class Child { 
@Output() notify: EventEmitter<string> = new EventEmitter<string>(); 

constructor() {} 
submit(){ 
    this.notify.emit(); 


    } 
} 

그리고 부모 클래스 템플릿에서

:

<child (notify)="toast.present();"></child > 
+0

감사합니다. –

0
  1. ECMA 6.0에서이 를 도입는 JAVA 정확히 유사한 작동 키워드를 확장 . 이 키워드는 상위 클래스의 모든 구성원에 액세스 할 수있는 하위 클래스를 만들어 클래스를 확장하는 데 사용됩니다.

  2. 부모 클래스의 멤버 중 하나에 액세스하려면 "super"이라는 키워드를 사용합니다. 이러한 부모와 자식 클래스가 어떤 의미에서

    클래스의 부모 { 생성자() {

      } 
    
         present() { 
    
         } 
        } 
    
    
         class Child extends Parent { 
          constructor() { 
          super(); 
          } 
    
          submit(){ 
          super.present(); // here **super** represents an instance of Parent class 
          } 
    
         }