【发布时间】:2018-11-23 10:13:27
【问题描述】:
我是 Angular 4 的新手,我正在尝试创建一个在加载某些内容时显示加载框的组件...例如登录、加载图表等。我不想使用插件这样做是因为我想学习如何去做。 我使用 CLI 命令 ng g component loading 创建了组件,然后创建了一个服务,该服务调用一个方法来显示或隐藏组件。
loading.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-loading',
templateUrl: './loading.component.html',
styleUrls: ['./loading.component.scss']
})
export class LoadingComponent implements OnInit {
private loading = false;
constructor() { }
ngOnInit() {
}
public showLoad(){
this.loading = true;
}
public hideLoad(){
this.loading = false;
}
}
loading.component.html
<div class ="box-loading" *ngIf="loading">
<div id="loading"></div>
</div>
loading.service.ts
import { Injectable } from '@angular/core';
import { LoadingComponent } from '../../loading/loading.component';
@Injectable()
export class LoadingService {
constructor(private loading: LoadingComponent) { }
public showLoading(){
this.loading.showLoad();
}
public hideLoading(){
this.loading.hideLoad();
}
}
当我调用showLoading() 方法时,什么也没有发生。所以我决定在我的登录页面上测试<app-loading></app-loading>,但我得到了以下错误。
ERROR Error: Uncaught (in promise): Error: Template parse errors:
'app-loading' is not a known element:
1. If 'app-loading' is an Angular component, then verify that it is part of this module.
2. If 'app-loading' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
<div class="login-box card">
<div class="card-body">
[ERROR ->]<app-loading *ngIf="loading"></app-loading>
<form class="form-horizontal floating-labels" id="log"): ng:///LoginModule/LoginComponent.html@4:3
我在 loading.module.ts 和 app.module.ts 中的 ngModule 中添加了 CUSTOM_ELEMENTS_SCHEMA。
加载.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoadingComponent } from './loading.component';
@NgModule({
declarations: [LoadingComponent],
exports: [LoadingComponent],
imports: [LoadingComponent],
schemas: [ CUSTOM_ELEMENTS_SCHEMA]
})
export class LoadingModule{}
如何将我的组件注入 html 页面?有最佳做法吗?我走对了吗?
【问题讨论】:
-
简短的回答是,你不能。您不能将组件作为依赖项注入。但是,还有很多选择。
-
您需要做的就是将您的组件添加到您的
app.module.ts文件或功能模块中的entryComponents数组中。 angular.io/guide/entry-components
标签: angular typescript angular-services angular-components