首页 > 其他分享 >Angular learning 20230206

Angular learning 20230206

时间:2023-02-06 09:11:05浏览次数:49  
标签:product component ts Product html learning import Angular 20230206

ng generate component 模块名 (有分包,以及html ts等)
ng generate service 服务名 (没分包,也没有html,只有ts)

component中引入service使用

@Component注解在ts中使用,实现了对对应分包内,在内部指定的
html或css的支撑

import { Component,OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Product,products } from '../products';
import { CartService } from '../cart.service';

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

  product: Product | undefined
  constructor(private route: ActivatedRoute,
              private cartService: CartService) { }

  addToCart(product: Product) {
    this.cartService.addToCart(product);
    window.alert('Your product has been added to the cart!')
  }

  ngOnInit(): void {
    const routeParams = this.route.snapshot.paramMap;
    const productIdFromRoute = Number(routeParams.get('productId'));
    this.product = products.find(product => product.id === productIdFromRoute)
  }

}

如上,该ts文件对html以及css做了product以及addToCart的方法支撑。
在html中调用时,就可以完全使用了。

<h2>Product Details</h2>

<div *ngIf="product">
  <h3>{{ product.name }}</h3>
  <h4>{{ product.price | currency }}</h4>
  <p>{{ product.description }}</p>
  <button type="button" (click)="addToCart(product)">Buy</button>
</div>

标签:product,component,ts,Product,html,learning,import,Angular,20230206
From: https://www.cnblogs.com/ukzq/p/17094394.html

相关文章