为数组中的每个元素创建html元素(角度)

时间:2018-07-31 11:42:35

标签: javascript html css angular typescript

我有Angular组件

这是代码

    @Component({
  selector: 'app-testcomponent',
  templateUrl: './testcomponent.component.html',
  styleUrls: ['./testcomponent.component.scss']
})
export class TestcomponentComponent implements OnInit {

  version: string = environment.version;
  error: string;
  searchForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private http: HttpClient
    ) {
    this.createForm();
   }

  ngOnInit() {}

  search() {
    this.http.get('https://api.chucknorris.io/jokes/search?query='+this.searchForm.value.jokevalue ).subscribe(
    data => [
      console.log(data)
    ])
  }

  private createForm() {
    this.searchForm = this.formBuilder.group({
      jokevalue: ['', Validators.required],
    });
  }
}

函数search()与从API获取值有关,并为提交按钮上数组中的每个元素进行html标记。这是模板html

<div class="container-fluid">
  <form class="form-inline" (ngSubmit)="search()" [formGroup]="searchForm" novalidate>
      <label for="text">Enter value:</label>
      <input formControlName="jokevalue" style="margin-left:20px;" type="text" class="form-control" id="email">
      <button style="margin-left:20px;" type="submit" class="btn btn-primary">Submit</button>
  </form>

获取数组已完成,这是响应数组

  

{     “类别”:null,     “ icon_url”:“ https://assets.chucknorris.host/img/avatar/chuck-norris.png”,     “ id”:“ cq6hLP0ETeW4VSrm7SYg5A”,     “ url”:“ https://api.chucknorris.io/jokes/cq6hLP0ETeW4VSrm7SYg5A”,     “值”:“查克·诺里斯(Chuck Norris)知道WAZZZUP!”   }

所以现在我需要从数组循环(它可以有多个元素)并为每个元素创建html标记

例如这个

<div>
<p>Number of array element</p>
<p>"value"</p>
</div>

我尝试这样做

 data => [
  for (let i = 0; i < data.length; i++) {

  }
])

但似乎不对。

我该如何解决我的问题。

谢谢

1 个答案:

答案 0 :(得分:8)

将数据公开在组件源中:

  public jokes: any[]; //or create an interface instead of using "any" for "strong" typing support

  search() {
    this.http.get('https://api.chucknorris.io/jokes/search?query='+this.searchForm.value.jokevalue ).subscribe(
    data => [
      console.log(data)
      this.jokes = data;
    ])
  }

在组件模板中使用*ngFor对数据进行bind

<div *ngFor="let joke of jokes">
    <p>{{joke.category}}</p>
    <p>{{joke.value}}</p>
</div>

更新有关不使用数组的注释:

将数据公开在组件源中:

  public joke: any; //or create an interface instead of using "any" for "strong" typing support

  search() {
    this.http.get('https://api.chucknorris.io/jokes/search?query='+this.searchForm.value.jokevalue ).subscribe(
    data => [
      console.log(data)
      this.joke = data;
    ])
  }

组件模板:

<div>
    <p>{{joke.category}}</p>
    <p>{{joke.value}}</p>
</div>