Angular中的@Input装饰器用于接收父组件传递给子组件的数据。下面是一个示例:
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
parentName = 'John Doe';
}
子组件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Welcome, {{ name }}!
`
})
export class ChildComponent {
@Input() name: string;
}
在上面的示例中,父组件通过属性绑定将parentName
传递给了子组件的name
属性。子组件通过@Input()
装饰器来接收父组件传递的数据,并将其显示在模板中。
除了@Input装饰器,Angular还提供了其他一些常用的装饰器,用于解决不同的问题。以下是一些常见问题及其解决方法:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent {
@Output() notify: EventEmitter = new EventEmitter();
notifyParent() {
this.notify.emit('Hello from child component!');
}
}
父组件中监听子组件事件的例子:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
handleNotification(message: string) {
console.log(message); // 输出:Hello from child component!
}
}
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
@ViewChild(ChildComponent) child: ChildComponent;
callChildMethod() {
this.child.childMethod();
}
}
子组件中的方法:
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `Child Component
`
})
export class ChildComponent {
childMethod() {
console.log('Child method called from parent component!');
}
}
上述示例中,通过@ViewChild装饰器将子组件的实例赋值给了child
属性,然后可以在父组件中调用子组件的方法。
这些示例展示了如何使用@Input装饰器以及其他一些常用装饰器来解决Angular中的问题。希望能对你有所帮助!