Angular2 [innerHtml] angular2 tag doesn't work

前端 未结 4 933
忘掉有多难
忘掉有多难 2021-01-15 13:49

I want to inject html in my a-component with angular2 tags from another component.

@Component({
  selector: \'app-root\',
  template: \'

        
4条回答
  •  自闭症患者
    2021-01-15 14:30

    There are a couple ways that you can do this.

    COMPONENT INTERACTION

    If there is a parent/child relationship between the components then you can use Input() and Output() to pass values between them

    This child component gets the value through the Input()

    child.component.ts

    import { Component, Input } from '@angular/core';
    @Component({
      selector: 'child',
      template: '
    {{myHtml}}
    ', // these curly braces add the text as innerHTML providers: [ FoodsService] }) export class ChildComponent implements OnInit { @Input() myHtml: string; }

    which is passed from the parent through the template:

    parent.component.html

    
    

    You can use Output() to go from child to parent.

    SERVICES

    The other way is to create a service that gets injected into both components. One component can send a value to the service and the other can get that value. In Angular2 this is often achieved by using observables to a data object.

提交回复
热议问题