如何实例化带参数的Angular个组件?
How to instantiate Angular components with parameters?
我一直在尝试通过传递 nameFilter = new FilterComponent("Name");
之类的参数来实例化组件,但我收到了这个错误:
NullInjectorError: No provider for String!
我相信依赖注入会导致这种情况,因为如果我不向组件注入任何东西,我就不会收到任何错误。那么究竟是什么原因造成的,我该如何解决?
这是组件代码
import { Component, OnInit, Inject } from '@angular/core';
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.scss']
})
export class FilterComponent implements OnInit {
title: String;
constructor(title: String) {
this.title = title;
}
ngOnInit() {
}
}
错误很明显,你是对的,是依赖注入机制导致的。您传递给构造函数的每个依赖项都必须在 运行 时注入,并且 Angular 需要知道要传递什么。
在你的情况下,Angular 不知道要注入什么作为字符串 title
。
您可以明确地告诉 Angular 在您的 String 类型的模块提供程序数组中注入什么。但是,这意味着每次都会使用您在 providers 数组中提供的任何内容。
@NgComponent({
...
providers: [
{ provide: String, useValue: 'my title' }
],
})
查看您的代码后,您可以使用 @Input
变量初始化组件 - Angular component interaction
export class FilterComponent implements OnInit {
@Input() title: string;
}
<app-filter [title]="Title 1"></app-filter>
作为一种良好的设计实践,避免 在组件构造函数中注入原始数据类型,如 string
、number
、date
等。
但是如果你还需要注入它们。然后你应该让 Angular 知道令牌和将要注入的值。
为此Angular提供了InjectionToken
API。 https://angular.io/api/core/InjectionToken#injectiontoken
在组件中注入日期类型的示例:
export const DATE = new InjectionToken<Date>('date');
@NgComponent({
...
providers: [
{ provide: DATE, useValue: new Date() } //can be declared at the module as well
],
})
export class SomeComponent {
constructor(
@Inject(DATE) private fromDate: Date,
@Inject(DATE) private toDate: Date
) {}
}
我一直在尝试通过传递 nameFilter = new FilterComponent("Name");
之类的参数来实例化组件,但我收到了这个错误:
NullInjectorError: No provider for String!
我相信依赖注入会导致这种情况,因为如果我不向组件注入任何东西,我就不会收到任何错误。那么究竟是什么原因造成的,我该如何解决?
这是组件代码
import { Component, OnInit, Inject } from '@angular/core';
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.scss']
})
export class FilterComponent implements OnInit {
title: String;
constructor(title: String) {
this.title = title;
}
ngOnInit() {
}
}
错误很明显,你是对的,是依赖注入机制导致的。您传递给构造函数的每个依赖项都必须在 运行 时注入,并且 Angular 需要知道要传递什么。
在你的情况下,Angular 不知道要注入什么作为字符串 title
。
您可以明确地告诉 Angular 在您的 String 类型的模块提供程序数组中注入什么。但是,这意味着每次都会使用您在 providers 数组中提供的任何内容。
@NgComponent({
...
providers: [
{ provide: String, useValue: 'my title' }
],
})
查看您的代码后,您可以使用 @Input
变量初始化组件 - Angular component interaction
export class FilterComponent implements OnInit {
@Input() title: string;
}
<app-filter [title]="Title 1"></app-filter>
作为一种良好的设计实践,避免 在组件构造函数中注入原始数据类型,如 string
、number
、date
等。
但是如果你还需要注入它们。然后你应该让 Angular 知道令牌和将要注入的值。
为此Angular提供了InjectionToken
API。 https://angular.io/api/core/InjectionToken#injectiontoken
在组件中注入日期类型的示例:
export const DATE = new InjectionToken<Date>('date');
@NgComponent({
...
providers: [
{ provide: DATE, useValue: new Date() } //can be declared at the module as well
],
})
export class SomeComponent {
constructor(
@Inject(DATE) private fromDate: Date,
@Inject(DATE) private toDate: Date
) {}
}