我正在尝试通过在指令中调用 API 来显示 API 数据,任何人都可以帮助我。
应用程序组件.html
<label>Display Titles</label>
<select class="rounded-inputs20
select-select col-md-3">
<option appDropdown></option>
</select>
dropdown.directive.ts
import {
HttpClient
} from '@angular/common/http';
import {
Directive
} from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
displaytitle: any;
constructor(private http: HttpClient) {}
gettitle() {
this.http
.get('https://jsonplaceholder.typicode.com/todos')
.subscribe(data => {
this.displaytitle = data;
console.log('titles', data);
});
}
}
https://stackblitz.com/edit/angular-dropdown-bfrzcs?file=dropdown.directive.ts
我真的不喜欢在指令中使用 HTTP 请求,但这里有您的解决方案。
import { HttpClient } from '@angular/common/http';
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
displaytitle: any;
constructor(
private http: HttpClient,
private el: ElementRef
) {
el.nativeElement.innerHTML = this.gettitle();
}
gettitle() {
this.http
.get('https://jsonplaceholder.typicode.com/todos')
.subscribe(data => {
Object.values(data).forEach((e) => this.el.nativeElement.innerHTML += `<option>${e.title}</otpion>`);
});
}
}
您必须“获取”当前元素才能处理它并写入数据。所以使用ElementRef
.
<select class="rounded-inputs20 select-select col-md-3" appDropdown>
</select>
为了编写每个选项,您必须使用directive
inselect
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句