Home > front end >  pass html input element variable to shared component
pass html input element variable to shared component

Time:11-18

Hello I have two components. Component 1 has a input-element to upload videos. It has a variable file

<input
  type="file"
  accept=".mp4"
  #file
/>

Now I have Component2 which is a shared component:

<button (click)="file.click()">upload video</button>

Now I need the "file" variable passed to the shared component to execute the file.click();

I can't take the input element in the shared component

https://stackblitz.com/edit/angular-ivy-9wi6qs?file=src/app/component1/component1.component.html

CodePudding user response:

This is as simple as sending the value into the component:

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {

  constructor() { }
   
  public fileAddress: string;

  public fileChanged(event) {
     // read the file when it changes and store it locally
     if(event.target.files.length > 0) 
         this.fileAddress = event.target.files[0].name;
     }
  }

  ngOnInit() {
  }

}
<!-- bind the event handler -->
<input type="file" accept=".mp4" (change)="fileChanged($event)" />
<!-- bind the local variable to an input on the child component -->
<app-upload-video [fileAddress]="fileAddress"></app-upload-video>
@Component({
  selector: 'app-upload-video',
  templateUrl: './upload-video.component.html',
  styleUrls: ['./upload-video.component.css']
})
export class UploadVideoComponent implements OnInit {

  //input variable to receive the value inside the component
  @Input()
  public fileAddress: string;

  constructor() { }

  ngOnInit() {
  }

}
  • Related