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

问题描述

我正在尝试通过在指令中调用 API 来显示 API 数据,任何人都可以帮助我。
app.component.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

标签: angular

解决方案


I really don't like using an HTTP request inside a directive, but here you are the solution.

Directive

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>`);
      });
  }
}

You have to "take" your current element to be able to handle it and write your data. So use ElementRef.

Component template

<select class="rounded-inputs20 select-select col-md-3" appDropdown>
</select>

In order to write every option, you have to use the directive in select


推荐阅读