英文:
How to define parameters in Angular components?
问题
我有一个名为modal的组件,它具有一个darkUnderneath属性。我试图在父组件的模板中使用[darkUnderneath]="true"进行绑定,并且出现了以下错误:
无法绑定到
modal的darkUnderneath属性,因为它不是modal的已知属性。
我需要使用@Output装饰器吗?我尝试了在@angular/core中定义darkUnderneath,无论是否使用了@Output装饰器。
<modal [darkUnderneath]="blah"></modal>
export class ModalComponent implements OnInit {
@Output()
darkUnderneath: boolean = false;
// ...
}
英文:
I've a component modal which has a darkUnderneath property. I'm trying to bind it using [darkUnderneath]="true" in my parent component's template and am getting:
> Can't bind to 'darkUnderneath' since it isn't a known property of 'modal'.
Do I need to use the @Output decorator? I tried defining darkUnderneath with and without the @Output decorator from @angular/core.
<modal [darkUnderneath]="blah"></modal>
export class ModalComponent implements OnInit {
@Output()
darkUnderneath: boolean = false;
// ...
}
答案1
得分: 2
你正在寻找@Input装饰器。
英文:
You're looking for the @Input decorator.
export class ModalComponent implements OnInit {
@Input()
darkUnderneath: boolean = false;
// ...
}
答案2
得分: 2
在Angular中,当您想要从子组件传递数据到父组件时,您需要使用@Output()装饰器以及一个EventEmitter。然而,您的问题中似乎存在一些混淆。如果您想要从父组件传递数据到子组件,您应该使用@Input()装饰器,而不是@Output()。
为了澄清这两种情况,以下是在子组件和父组件之间传递数据时使用@Input()和@Output()装饰器的正确方法:
从父组件传递数据到子组件(使用@Input()):
父组件(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: '<app-child [dataFromParent]="data"></app-child>',
})
export class ParentComponent {
data: string = "Data from Parent";
}
子组件(child.component.ts):
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ dataFromParent }}</p>',
})
export class ChildComponent {
@Input() dataFromParent: string;
}
希望这能帮助您清楚地理解。
英文:
In Angular, when you want to pass data from a child component to a parent component, you need to use the @Output() decorator along with an EventEmitter. However, it seems there might be a slight confusion in your question. If you want to pass data from the parent component to the child component, you use @Input() decorators, not @Output().
To clarify both scenarios, here's the proper way to use @Input() and @Output() decorators for data passing between child and parent components:
Passing data from Parent to Child (using @Input()):
Parent Component (parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: '<app-child [dataFromParent]="data"></app-child>',
})
export class ParentComponent {
data: string = "Data from Parent";
}
Child Component (child.component.ts):
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '<p>{{ dataFromParent }}</p>',
})
export class ChildComponent {
@Input() dataFromParent: string;
}
I hope it will help you to understand clearly
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论