Ich habe eine Komponente, die die Funktion als Eingabe übernimmt. Ich habe diese Funktion von Eltern übergeben.
Obwohl die Funktion aufgerufen wird, kann die Funktion nicht auf die Abhängigkeiten der Instanz zugreifen, für die diese Funktion deklariert ist.
Hier ist die Komponente
@Component({
selector: 'custom-element',
template: `
{{val}}
`
})
export class CustomElement {
@Input() valFn: () => string;
get val(): string {
return this.valFn();
}
}
So wird die Komponente verwendet
@Injectable()
export class CustomService {
getVal(): string {
return 'Hello world';
}
}
@Component({
selector: 'my-app',
template: `
<custom-element [valFn]="customVal"></custom-element>
`,
})
export class App {
constructor(private service: CustomService) {
}
customVal(): string {
return this.service.getVal();
}
}
Wenn ich diese App starte, erhalte ich eine Fehlermeldung in der Konsole, die Cannot read property 'getVal' of undefined
sagt.
Hier ist ein Plunker für die Ausgabe.
Sie müssen .bind(this)
, wenn Sie Methoden herumgeben:
<custom-element [valFn]="customVal.bind(this)"></custom-element>
oder
export class App {
constructor(private service: CustomService) {
}
customVal(): string {
return this.service.getVal();
}
customValFn = this.customVal.bind(this);
}
mit
<custom-element [valFn]="customValFn"></custom-element>
Sie können eine get/set -Eigenschaft anstelle einer Funktion auf ähnliche Weise wie folgt übergeben:
Irgendwo in deiner Sicht:
<input type="text" [(ngModel)]="yourprop">
In Ihrer Komponentendatei:
@Component({
selector: 'myapp',
templateUrl: './myapp.component.html',
styleUrls: ['./myapp.component.scss']
})
export class App {
constructor() { }
yourprop: any;
get yourprop(): any {
return this.scheduleEndDate;
};
//set accessor including call the onchange callback
set yourprop(v: any) {
// TODO do something else
// You can do whatever you want just like you have passed a function
if (v !== this.scheduleEndDate) {
this.scheduleEndDate = v;
}
}
}
mehr info @ https://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel