页面加载时应该已经选择了第一个条目并显示其内容,该怎么做?

there should be already the first entry selected and its content shown when the page loads, how to do that?

我创建了一个 ngModel 和 ngchange,它们绑定到 ts 文件中的 json 数组并显示其内容。

第一个条目 selected 应该已经存在,页面加载时会显示其内容。我想在 selected 之前显示默认下拉值并显示其内容。截至目前,加载时只有空白屏幕,当我 select 下拉菜单然后加载内容时。

我试图先显示默认内容,然后如果用户点击它,它就会改变。

App.component.html

'''
<div>
    Select Product :
    <select [(ngModel)]="ProductHeader.name" (ngModelChange)="SearchProduct(ProductHeader.name)">
        <option *ngFor="let prod of ProductHeader">{{prod.name}} </option>
    </select>



    <div *ngIf="ProductHeader.name">
        <h5>You have selected: {{ProductHeader.name}} Product </h5>
    </div>
</div>
<div>
    <h4>Product Details:</h4>
    <table class="TFtable">
        <tr>
            <th>Name</th>
            <th>Store</th>
            <th>Price</th>
            <th>Model</th>
        </tr>
        <tr *ngFor="let Prod of ProductDetails">
            <td>{{Prod.title}}</td>
            <td>{{Prod.store}}</td>
            <td>{{Prod.price}}</td>
            <td>{{Prod.model}}</td>
        </tr>

'''

App.component.ts

'''

import { Component, Input, OnInit } from '@angular/core';

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

  public ProductDetails: any = [];

  //filter product details on name and return productDetails object.

  public ProductHeader: any = 
[{ name: 'Hp' }, { name: 'Dell' }, { name: 'Lenovo' }];

  stringifiedData: any;
  data: any;
  stringData: any;
  parsedJson: any;

  ngOnInit() {

    this.stringifiedData = JSON.stringify(this.Products);
    console.log("With Stringify :", this.stringifiedData);

    // Parse from JSON  
    this.parsedJson = JSON.parse(this.stringifiedData);
    console.log("With Parsed JSON :", this.parsedJson);


  }



  public Products = [
    { Name: 'Hp', title: 'HP ENVY Laptop - 15t touch', price: '1099', store: 'Best Buy', model: '15-BS013DX' },
    { Name: 'Dell', title: 'Dell Laptop', price: '700', store: 'Amazon', model: 'I7378-3000SLV-PUS' },
    { Name: 'Lenovo', title: 'Lenovo Touch-Screen Laptop', price: '670', store: 'Target', model: '81A40025US' },
    { Name: 'Hp', title: 'HP OfficeJet Pro 6978 All-in-One Printer', price: '100', store: 'Target', model: 'T0F29A#B1H' },
    { Name: 'Hp', title: 'HP Laptop - 17t touch ', price: '420', store: 'Target', model: '1EZ78AV_1' },
    { Name: 'Dell', title: 'Dell - XPS 27" Touch-Screen All-In-One', price: '670', store: 'Target', model: 'BBY-311C3FX' },
    { Name: 'Dell', title: 'Dell - Inspiron 21.5" Touch-Screen All-In-One', price: '469.90', store: 'Target', model: 'I3265-A067BLK-PUS' },
    { Name: 'Lenovo', title: 'Lenovo - 520-24AST 23.8" Touch-Screen All-In-One', price: '679.99', store: 'Target', model: 'F0D3000EUS' },
    { Name: 'Dell', title: 'Dell - XPS 2-in-1 13.3" Touch-Screen Laptop', price: '1199.99', store: 'Target', model: 'XPS9365-7086SLV-PUS' }
  ];

  constructor() {

    this.getProducts();
  }
  getProducts() {
    console.log("getProducts");
    return this.ProductHeader;
  }
*Search products searches the name and displays the value*

  SearchProduct(name: string) {

    let obj = this.Products.filter(m => m.Name == name);
    this.ProductDetails = obj;
    return this.ProductDetails;
  }


}

**Do check how to select the  default dropdown value**

'''

抱歉,为了使其正常工作,我不得不稍微重构一下您的代码。

HTML

提示 1

当您使用 [(ngModel)] 时,将它连接到一个单独的变量,您可以在其中读取和写入。我为此添加了 selectedProductModel。当你现在select一个ProductModel时,这个对象将被放入selectedProductModel,然后你可以调用searchProduct()而不需要提交任何进一步的值。

提示 2

select 中的一个选项必须有一个值才能使其工作。这就是我添加 [ngValue].

的原因

这里是你的精HTML.

<div>
  Select Product :
  <select [(ngModel)]="selectedProductModel" (ngModelChange)="searchProduct()">
    <option *ngFor="let productModel of productModels" [ngValue]="productModel">{{productModel.name}}</option>
  </select>
  <div *ngIf="selectedProductModel && selectedProductModel.name.length > 0">
    <h5>You have selected: {{selectedProductModel.name}} Product </h5>
  </div>
</div>
<div>
  <h4>Product Details:</h4>
  <table class="TFtable">
    <tr>
      <th>Name</th>
      <th>Store</th>
      <th>Price</th>
      <th>Model</th>
    </tr>
    <tr *ngFor="let prod of productDetails">
      <td>{{prod.title}}</td>
      <td>{{prod.store}}</td>
      <td>{{prod.price}}</td>
      <td>{{prod.model}}</td>
    </tr>
  </table>
</div>

TS

提示 3

类 以大写字母开头,但变量始终以小写字母开头。任何方法都一样,它们总是以小写字母开头。他们应该始终分配 return 值,即使它是 void.

提示 4

尝试定义一个您可以使用的模型。这样,当您尝试访问不存在的字段时,TypeScript 可以警告您。

这是您重构的 TS 文件。

import { Component, Input, OnInit } from '@angular/core';

// an object that represents a product detail.
class ProductDetails {
  constructor(
    public name: string,
    public title: string,
    public price: string,
    public store: string,
    public model: string
  ) {
  }
}

// an object that represents the product model
class ProductModel {
  constructor(
    public name: string
  ) {
  }
}

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

  // a list of product models
  public productModels: Array<ProductModel> = [
    new ProductModel('Hp'),
    new ProductModel('Dell'),
    new ProductModel('Lenovo')];

  // the currently selected product model. 
  // It is preset with the first product model of the list.
  selectedProductModel = this.productModels[0];

  // the list of product details. It gets filled by the `searchProduct()` method.
  productDetails: any[] = [];

  stringifiedData: any;
  data: any;
  stringData: any;
  parsedJson: any;

  // your list of product details
  public products = [
    new ProductDetails('Hp', 'HP ENVY Laptop - 15t touch', '1099', 'Best Buy', '15-BS013DX'),
    new ProductDetails('Dell', 'Dell Laptop', '700', 'Amazon', 'I7378-3000SLV-PUS'),
    new ProductDetails('Lenovo', 'Lenovo Touch-Screen Laptop', '670', 'Target', '81A40025US'),
    new ProductDetails('Hp', 'HP OfficeJet Pro 6978 All-in-One Printer', '100', 'Target', 'T0F29A#B1H'),
    new ProductDetails('Hp', 'HP Laptop - 17t touch ', '420', 'Target', '1EZ78AV_1'),
    new ProductDetails('Dell', 'Dell - XPS 27" Touch-Screen All-In-One', '670', 'Target', 'BBY-311C3FX'),
    new ProductDetails('Dell', 'Dell - Inspiron 21.5" Touch-Screen All-In-One', '469.90', 'Target', 'I3265-A067BLK-PUS'),
    new ProductDetails('Lenovo', 'Lenovo - 520-24AST 23.8" Touch-Screen All-In-One', '679.99', 'Target', 'F0D3000EUS'),
    new ProductDetails('Dell', 'Dell - XPS 2-in-1 13.3" Touch-Screen Laptop', '1199.99', 'Target', 'XPS9365-7086SLV-PUS')
  ];

  constructor() {
  }

  ngOnInit(): void {
    this.stringifiedData = JSON.stringify(this.products);
    console.log('With Stringify :', this.stringifiedData);

    // Parse from JSON
    this.parsedJson = JSON.parse(this.stringifiedData);
    console.log('With Parsed JSON :', this.parsedJson);

    // fire the search method. As productDetails is already preset with the 
    // first product model, your drowpdown has a selection and the result is shown.
    // this is what you were looking for.
    this.searchProduct();
  }

  searchProduct(): void {
    this.productDetails = this.products.filter(productDetail => productDetail.name === this.selectedProductModel.name);
  }

}