I have some upload directive, that is very simple, only problem is that i have to emit value from this directive component to parent component. Does anybody know a simple solution? Thanks in advance. This is my directive for now:
upload-field.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
@Component({
selector: 'app-upload-field',
templateUrl: './upload-field.component.html',
styleUrls: ['./upload-field.component.scss']
})
export class UploadFieldComponent implements OnInit {
@Input() labelName: string;
@Input() placeHolderValue: string;
value = '';
constructor() { }
ngOnInit() {
}
uploadButton(event: any) {
this.value += event.target.value;
this.value = this.value.replace(/^.*\\/, '');
}
}
upload-field.component.html
<input placeholder="{{placeHolderValue}}" disabled="disabled" class="form-control first-input" value="{{value}}" />
<div class="file-upload">
<span class="btn btn-default btn-lg">{{labelName}}</span>
<input type="file" class="form-control upload-button" (change)="uploadButton($event)" value="{{value}}" />
</div>
And I use it like this:
<app-upload-field [labelName]="'Blader'" [placeHolderValue]="'Kies bestand'"></app-upload-field>
You can use EventEmitter
for this.
Reference: Parent listens for child event
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
//...your decorator properties
})
export class UploadFieldComponent {
@Output() onValueChanged = new EventEmitter<any>();
uploadButton() {
this.value += event.target.value;
this.value = this.value.replace(/^.*\\/, '');
this.onValueChanged.emit(this.value);
}
}
In parent component, Template:
<app-upload-field [labelName]="'Blader'" [placeHolderValue]="'Kies bestand'"
(onValueChanged)=onValueChanged($event)>
</app-upload-field>
Within component code,
onValueChanged(value) {
// value will be the emitted value by the child
}
The child component exposes an
EventEmitter
property with which it emits events when something happens. The parent binds to that event property and reacts to those events.
In UploadFieldComponent
export class UploadFieldComponent implements OnInit {
...
@Output myValueChanged = new EventEmitter<string>();//passing a string value to parent
...
uploadButton(event: any) {
...
myValueChanged.emit(valueToBePassed);
}
}
Usage
<app-upload-field [labelName]="'Blader'" (myValueChanged)="parentEvent($event)" [placeHolderValue]="'Kies bestand'"></app-upload-field>
In parent component
parentEvent(data:string){
// do something with data
}
Refer this link for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.