首页 > 解决方案 > 另一个组件内的Angular 11打印组件

问题描述

我有一个简单的组件,我在其中放置了多个按钮,我想在另一个组件中显示这些按钮(按钮的功能也来自我的按钮组件)但我在终端中收到此错误

ERROR NullInjectorError: R3InjectorError(HelpdeskModule)[ButtonsComponent -> ButtonsComponent -> ButtonsComponent -> ButtonsComponent]: 
  NullInjectorError: No provider for ButtonsComponent!

代码

buttons.component.html

<div class="mb-3">
  <nz-button-group>
      <button nz-button nzType="primary" (click)="buttonClick('create button')" class="ant-btn ant-btn-primary ant-btn-lg"><i nz-icon nzType="download"></i>Create New</button>
  </nz-button-group>
</div>

list.component.ts(这是我想展示这些组件的地方)

  import { ButtonsComponent } from 'src/app/components/app/layout/buttons/buttons.component';

  constructor(
    private buttons: ButtonsComponent,
  ) { }

list.component.html

// I am uncertain about this part to be correct at all!
{{buttons}}

任何想法?

更新

我已经Injectable像这样添加到我的按钮组件中:(只是为了让它们打印出来)

import { Component, OnInit, Injectable } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd'


@Component({
  selector: 'app-buttons',
  templateUrl: './buttons.component.html',
  styleUrls: ['./buttons.component.scss']
})

@Injectable({
  providedIn: 'root'
})

export class ButtonsComponent implements OnInit {
  //
}

现在我收到了这个错误

ERROR TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

标签: javascriptangulartypescript

解决方案


首先,在里面list.component.html放置 html 如下所示

<app-buttons></app-buttons>

然后你想调用 of 的方法ButtonsComponent,将其用作依赖项,你必须先将它保存在 providers 数组中。

providers: [
  ...,
  ButtonsComponent,
  ...
]

但是当我查看您更新的问题时,您不必在构造函数中注入组件,而是可以使用ViewChild.

@ViewChild('buttons', { static: false, read: ViewContainerRef })
buttons: ButtonsComponent;

list.component.html

<app-buttons #buttons></app-buttons>

Stackblitz 演示


推荐阅读