如何使用参数实例化 Angular 组件? [英] How to instantiate Angular components with parameters?

查看:17
本文介绍了如何使用参数实例化 Angular 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试通过传递像 nameFilter = new FilterComponent("Name"); 这样的参数来实例化组件,但我收到了这个错误:

I've been trying to instantiate components by passing parameters like nameFilter = new FilterComponent("Name"); but I'm getting this error:

NullInjectorError: 没有 String 的提供者!

NullInjectorError: No provider for String!

我相信依赖注入会导致这种情况,因为如果我不向组件注入任何内容,我不会收到任何错误.那么究竟是什么原因导致了这种情况,我该如何解决呢?

I believe dependency injection causes this as I don't get any errors if I don't inject anything to component. So what exactly causes this and how can I fix it?

这是组件代码

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 需要知道要传入的内容.

The error is clear and you're right, the dependency injection mechanism is causing it. Every dependency you pass into the constructor must be injected at run-time and Angular needs to know what to pass in.

在您的情况下,Angular 不知道要注入什么作为字符串 title.

In your case, Angular does not know what to inject as the string title.

你可以明确地告诉 Angular 在你的模块提供程序数组中为 String 类型注入什么.但是,这意味着每次都将使用您在 providers 数组中提供的任何内容.

You can explicitly tell Angular what to inject in your module provider array for String type. However, this means that whatever you provide in the providers array will be used every time.

@NgComponent({
    ...
    providers: [
    { provide: String, useValue: 'my title' }
  ],
})

查看您的代码后,您可以使用 @Input 变量初始化组件 - Angular 组件交互

Having looked at your code, you can initialise the component with an @Input variable - Angular component interaction

export class FilterComponent implements OnInit {
     @Input() title: string; 
}

<app-filter [title]="Title 1"></app-filter>

简单演示:https://stackblitz.com/edit/angular-rs6sfy

这篇关于如何使用参数实例化 Angular 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆