javascript - 另一个组件内的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.
解决方案
首先,在里面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>
推荐阅读
- c# - {"ORA-01036: 非法变量名/编号"} - 更新最后一个数字序列 Oracle 数据库
- html - 使用 CSS 显示/隐藏分类项目
- java - 为什么此特定代码不适用于二叉搜索树?
- r - R中的匹配数据框
- android - android soundeffectsenabled 在 Scrollview 中不起作用
- sql - 使用触发器跟踪 PostgreSQL 表上插入、更新或删除的更改
- java - 如何在 JGROUPS 中禁用 FIFO 和重传协议?
- powershell - 仅压缩文件而非目录
- typescript - 当我使用 Bluebird.promisifyAll 时,打字稿无法推断类型
- c# - 如何访问大括号中的成员 { ID: 1, Name: John }