简体   繁体   English

在 TS 中添加 html 标签 Angular

[英]add html tag Angular in TS

I'm trying to make an editor by myself the problem I'm having is when I apply the bold style all my text becomes bold how do I make from my click the text becomes bold if there is already text it should not be bold?我正在尝试自己制作一个编辑器我遇到的问题是当我应用粗体样式时我的所有文本都变为粗体如何通过单击使文本变为粗体如果已经有文本它不应该是粗体?

the other question with my way of doing it doesn't add a我的做法的另一个问题并没有添加tag how to do it too?标签怎么办呢?

thanks in advance.提前致谢。

html html

  <form [formGroup]="form">
    <div>
      <mat-form-field appearance="outline">
        <mat-label>textarea</mat-label>
        <textarea #text matInput formControlName="editor"></textarea>
      </mat-form-field>
    </div>
  </form>

ts.file ts.文件

  @ViewChild('text') public textarea: ElementRef;

  public form: FormGroup;
  public isBold: boolean = false;

  constructor(private fb: FormBuilder, private renderer: Renderer2) {}

  ngOnInit(): void {
    this.createForm();
  }

  createForm() {
    this.form = this.fb.group({
      editor: null,
    });
  }

  addBoldStyle() {
    this.isBold = !this.isBold;
    if (this.isBold) {

      // let tag = document.createElement('strong');
      // let text = document.createTextNode(this.textarea.nativeElement.innerHTML);
      // tag.appendChild(text);

      this.textarea.nativeElement.style.fontWeight = 'bold';
    } else {
      this.textarea.nativeElement.style.fontWeight = null;
    }
  }

  add() {
    console.log(this.form.value);
  }

Let try to use让我们尝试使用

private renderer: Renderer2
...
this.renderer.setStyle(this.el.nativeElement, 'background', 'yellow');
this.renderer.setProperty(this.el.nativeElement, 'innerHTML', '<p>Hello World<p>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM