【发布时间】:2022-01-27 03:44:25
【问题描述】:
当我使用@ViewChild 时,我收到未定义组件的错误。 当我使用 @ViewChildren 时,我收到该组件中的函数不是函数的错误。
我不熟悉在 Angular 中使用子组件,所以当我确实在父组件中定义了子组件并且它显然是子组件中的一个函数时,我不确定它为什么会这样做。
我不想在父级中定义来自子级的每个函数,否则使用单独组件的意义何在。
子组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-mood',
templateUrl: './mood.component.html',
styleUrls: ['./mood.component.css']
})
export class MoodComponent implements OnInit {
moodColors = ['red', 'orange', 'grey', 'yellow', 'green'];
constructor() { }
ngOnInit(): void {
}
chooseMood() {
alert(this.moodColors);
}
}
父组件(带有“ERROR TypeError: ctx_r3.mood is undefined”的版本相关部分)
import { Component, OnInit, ViewChild, ViewChildren } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { MoodComponent } from '../mood/mood.component';
@Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CalendarComponent implements OnInit {
@ViewChild('mood') mood: MoodComponent = new MoodComponent;
父组件(带有“ERROR TypeError: ctx_r3.mood.chooseMood is not a function”的版本相关部分)
import { Component, OnInit, ViewChild, ViewChildren } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { MoodComponent } from '../mood/mood.component';
@Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CalendarComponent implements OnInit {
@ViewChildren('mood') mood: MoodComponent = new MoodComponent;
父视图
<h2 (click)="mood.chooseMood()"></h2>
【问题讨论】:
-
我忘了添加,我可以使用插值从父视图调用该子函数,所以我知道它可以看到它,但我不能将它用于我正在尝试做的事情。
标签: javascript html angular