반응형
자식 구성 요소의 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
반응형
'programing' 카테고리의 다른 글
| Javascript 요청에 대한 Rescue_from (0) | 2023.08.18 |
|---|---|
| jQuery 데이터 테이블을 다시 로드/새로 고침하는 방법은 무엇입니까? (0) | 2023.08.18 |
| mysql에서 고유 키를 함께 변경합니다. (0) | 2023.08.18 |
| 특정 '인라인 블록' 항목 앞/뒤에 줄 바꿈 CSS (0) | 2023.08.18 |
| Swift에서 하나 이상의 프로토콜을 준수하는 특정 유형의 변수를 선언하려면 어떻게 해야 합니까? (0) | 2023.08.18 |