Angular9入门(2)

制作一个简易的新闻发布页面

完成后的效果如下图所示:

Angular9入门(2)_第1张图片

 

1、新建一个angular应用

ng new angular9-reddit

2、添加css,案例的样式采用的是semantic ui。具体用法可以参考下面的网站,别参考那本书。

网站:https://1.semantic-ui.com/

  
  
  

这里下载对应的文件放在资源目录下,然后把链接放在首页的html模板中。这章css不重要,素颜也没事,只要能实现功能。

3、app.component.ts

import { Component } from '@angular/core';
import { Article } from './article/article.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular9-reddit';
  articles: Article[]
  constructor(){
    this.articles = [
      new Article('天龙八部','http://tianlong.com',10),
      new Article('武林外传','http://wulin.com',11),
      new Article('少年歌行','http://shaonian.com',18),
    ]
  }
  addArticle(title:HTMLInputElement,link:HTMLInputElement){
    if(title.value === ""){
      return false;
    }
    this.articles.push(new Article(title.value,link.value,0));
    title.value = ''
    link.value = ''
    return false
  }
  sorteArticles():Article[]{
    return this.articles.sort((a:Article,b:Article)=>b.votes -a.votes);
  }
}

4、app.compoent.html

添加一个链接

5、添加文章组件

ng generate component article

6、article.component.ts

import { Component, OnInit, Input } from '@angular/core';
import {Article} from './article.model'

@Component({
  selector: 'app-article',
  templateUrl: './article.component.html',
  styleUrls: ['./article.component.css'],
  host:{
    class:'row'
  }
})
export class ArticleComponent implements OnInit {
  @Input() article:Article
  @Input() iid:number
  voteUp(){
    this.article.votes += 1;
    return false
  }
  voteDown(){
    this.article.votes -= 1;
    return false
  }  
  ngOnInit(): void {

  } 
}

7、article.component.html

{{article.votes}}
票数

8、article.model.ts

export class Article {
    votes: number
    title: string
    link: string
    constructor(title:string,link:string,votes?:number) {
        this.title = title
        this.link = link
        this.votes = votes || 0
    }
    domain():string{
        try{
            const link :string = this.link.split('//')[1];
            return link.split('/')[0]
        } catch (err){
            return null
        }
    }
}

9、完成。

 

 

你可能感兴趣的:(Angular)