我想在指令中调用我的 API 并在我需要的地方使用指令。任何人都可以帮助我。请罚款我的例子

占西拉乌拉

我正在尝试通过在指令中调用 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

Shifenis

我真的不喜欢在指令中使用 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>

为了编写每个选项,您必须使用directiveinselect

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章