Search code examples
angularemit

Passing data between angular components


I have component1, which imports component2 and uses it's functions. this function calls dialog window from component2.

export class component1 implements OnInit {
  @Output() testVar= new EventEmitter();

    openDialog(){
    this.testVar.emit(200); 
    const dialogRef = this.dialog.open(Component2, {

Now I want somehow send variable to that component. So when second component OnInit it could get my variable, something like

export class Component2 implements OnInit {
 @Input() testVar;

somefunc() {
onUpload(testVar) {
  console.log(testVar) ;
}

Can you please write some example or give me the link? Problem is that I want to do this between .ts files without html.


Solution

  • You can pass a https://material.angular.io/components/dialog/api#MatDialogConfig in the dialog.open(Component2, { data: {testVar:'Hello'}})

     export class Component2 implements OnInit {
          constructor(  @Inject(MAT_DIALOG_DATA) public data: {testVar:string})
    
         somefunc() { 
             console.log(this.data.testVar) ;
          }