程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Angular 12 - 改变注入组件的值而不更新 html大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Angular 12 - 改变注入组件的值而不更新 html?

开发过程中遇到Angular 12 - 改变注入组件的值而不更新 html的问题如何解决?下面主要结合日常开发的经验,给出你关于Angular 12 - 改变注入组件的值而不更新 html的解决方法建议,希望对你解决Angular 12 - 改变注入组件的值而不更新 html有所启发或帮助;

我开始使用依赖注入在我的所有组件中注入一个 AlertComponent便能够在任何地方显示警报,但我无法让它工作......

警报组件:

import { Component,OnInit,VIEwChild } from '@angular/core';
import { Subject } from 'rxJs';
import { debounCETime } from 'rxJs/operators';
import { NgbAlert } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';

@Component({
  SELEctor: 'app-alert',templateUrl: './alert.component.HTML',styleUrls: ['./alert.component.sCSS']
})

@Injectable()

export class AlertComponent implements OnInit {
  private _success = new Subject<String>();

  successmessage = '';
  typeAlert = 'success';

  @VIEwChild('selfClosingalert') selfClosingalert: NgbAlert;

  ngOnInit(): voID {

    this._success.subscribe(message => this.successmessage = messagE);
    this._success.pipe(debounCETime(5000)).subscribe(() => {
      if (this.selfClosingalert) {
        this.selfClosingalert.close();
      }
    });
  }

  public NewAlert(message: String)
  {
    this.typeAlert = "success";
    this._success.next(messagE);
  }

  public NewDangerAlert(message: String)
  {
    this.typeAlert = "danger";
    this._success.next(messagE);
  }

  public NewWarningalert(message: String)
  {
    this.typeAlert = "warning";
    this._success.next(messagE);
  }
}

他的 HTML(我在 index.HTML 中添加了 <app-alert></app-alert>

<ngb-alert #selfClosingalert *ngIf="successmessage" type={{typeAlert}} (closed)="successmessage = ''">
  {{ successmessage }}
</ngb-alert>

使用它的组件示例:

import { AlertComponent } from '../alert/alert.component'

@Component({
  provIDers: [AlertComponent],SELEctor: 'app-document-download',templateUrl: './document-download.component.HTML',styleUrls: ['./document-download.component.sCSS']
})

export class documentDownloadComponent implements OnInit {
  alerte: AlertComponent = null

  constructor(alerte: AlertComponent) {
    this.alerte = alerte;
  }

  onsubmit() {
    this.alerte.NewWarningalert("Hello,this is a test.")
  }
}

当我直接从 NewWarningalert 而不是从我的 documentDownloadComponent 调用它时,使用 AlertComponent 函数有效。

感谢您的帮助!

解决方法

我找到了一个解决方案,我不知道它是否是最好的:

DocumentDownloadComponent 中,我将 alerte: AlertComponent = null 更改为 @ViewChild(AlertComponent) alerte: AlertComponent;(不再需要在构造函数中实例化它)。

还必须在 DocumentDownloadComponent html、<app-alert></app-alert> 中添加选择器。

大佬总结

以上是大佬教程为你收集整理的Angular 12 - 改变注入组件的值而不更新 html全部内容,希望文章能够帮你解决Angular 12 - 改变注入组件的值而不更新 html所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。