0
votes

These are my code

child.component.ts

import { Component, Input, OnInit, EventEmitter, Output } from '@angular/core';
import { DomSanitizer } from "@angular/platform-browser";

@Component({
  selector: 'child-component',
  templateUrl: './child.component.html',
})
export class ChildComponent implements OnInit {
  @Input() dataFromParent: String;
  @Output() sendDataToParent = new EventEmitter<string>();
  htmldata:any;

  constructor(private sanitizer: DomSanitizer){

  }

  ngOnInit() {
    this.htmldata = '<input type="text" #data><button (click)="_sendDataToParent(data.value)">Send event to parent</button>';

    console.log('This is data from parents', this.dataFromParent);
    console.log('this.htmldata', this.htmldata);
  }

  _sendDataToParent(data:string) {
    console.log('you clicked');
    this.sendDataToParent.emit(data);
  }

  makeSanitize(str: any)
  {
    return this.sanitizer.bypassSecurityTrustHtml(str);
  }
}

child.component.html

<h2>Child Component</h2>
<p>{{dataFromParent}}</p>
<span [innerHTML]="makeSanitize(htmldata)"></span>

app.component.html

<h2>Parent Component</h2>
<p>
    {{dataFromChild}}
</p>

<hr>
<hr>
<hr>

<child-component 
  [dataFromParent]="'This is data sent from parent'"
  (sendDataToParent)="eventFromChild($event)">
</child-component>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  dataFromChild;
  eventFromChild(data) {
    console.log(data);
    this.dataFromChild = data;
  }
}

I planned to generate htmldata dynamically.

htmldata has innerhtml values in its child component. Innerhtml also have Click event which is not working.

I want to fill the input and click the Send event to parent button. But the event was not triggered.

Dear developers please help me

1
Friends please anyone guide me - carte

1 Answers

1
votes

You are coding "angular" in a string value and then putting it into the DOM. The angular code needs to be compiled to be transformed in real html/js code

Thus you need to start by writing "onclick" instead of "(click)" But then you will have other error like "_sendDataToParent is not defined" because you would need that function a "script" tag

See here to test https://stackblitz.com/edit/angular-4s9fzs

In the end, producing angular code in a string and then putting it into the DOM is probably something you don't want to do