首页 > 解决方案 > 角度错误:无法解析组件的所有参数

问题描述

我正在为 Udemy 课程做一个 Angular 练习,遇到了一个我无法解决的问题。我正在尝试创建一个具有唯一 ID 的 ClickComponent 对象,因此每个对象都有下一次迭代(即 1、2、3 等)。但是,当我尝试向构造函数添加参数以从调用它的类中获取此 id 时,出现上述错误。以下是两个相关文件:

app.component.ts

import { Component } from '@angular/core';
import {ClickComponent} from './click/click.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  display = false;
  clicks = [];

  toggleDisplay() {
    this.clicks.push(new ClickComponent(this.clicks.length + 1));
    this.display = !this.display;
  }
}

点击.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-click',
  templateUrl: './click.component.html',
  styleUrls: ['./click.component.css']
})
export class ClickComponent implements OnInit {
  id;
  timeStamp;

  constructor(id: number) {
    this.id = 0;
    this.timeStamp = new Date();
  }

  ngOnInit() {
  }

}

如果我从点击构造函数中删除参数并将id设置为0,错误就会消失,所以它显然与我如何设置该构造函数有关,但我不明白有什么问题,因为我是全新的到角。谢谢。

标签: angulartypescript

解决方案


我认为您不应该将 id 放在构造函数中,而是将 @Input() 放在 id 字段之前。
这就是参数以角度从父母传递给孩子的方式。

编辑:
如果您想知道如何将参数传递给动态创建的组件,请查看另一个线程: Angular2 - Pass values to a dynamic component created with ComponentFactory


推荐阅读