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

查看:65
本文介绍了如何使用参数实例化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:没有字符串提供程序!

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 变量初始化组件-

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天全站免登陆