如何通过从列表中选择项目来解锁按钮?

问题描述 投票:1回答:2

我希望并且仍然希望这样做,当您单击列表中的一个项目时,按钮被解锁,以便以某种方式将所选项目以彩色突出显示。这是我的工件不起作用(告诉我你如何实现这个动作。

HTML:

<div class="card">
  <div class="row">
    <div class="card-content table-responsive ">
      <div class="col-md-12">
        <a (click)="SelectedPost(post?.post_id)">
          <table class="table table-hover">
            <thead>
              <tr>
                <th>Name</th>
              </tr>
            </thead>
            <tbody>
              <tr  *ngFor="let post of posts">
                <td>{{post.name}} </td>
              </tr>
            </tbody>
          </table>
        </a>
      </div>
      <div class="col-md-12">
      <button type="submit" [disabled]="!selectedPost" class="btn btn-info pull-right">Ok</button>
  </div>
</div>

TS:

...
export class PostComponent  implements ModalComponent<any> {

  posts: Array<Post>;
  selectedPost = null;

  constructor(
    public dialog: DialogRef<any>, 
    public authTokenService: Angular2TokenService, 
    private servPost: SprPostService
  ) { 
    this.sprPosts = new Array<Post>();
  }

  ngOnInit() {
    this.loadPosts();
  }

  private loadPosts() {
    this.servPost.getPosts().subscribe(posts => this.posts = posts);
  }

  SelectedPost(PostId) {
    this.selectedPost = this.posts.find(el => {
      return el.post_id === PostId
    })
  }

}
angular
2个回答
1
投票

您的帖子列表将遍历* ngFor。每个tr将显示列表的每个记录。所以没有tr将是你的帖子列表。您必须在tr上应用selectedPost()函数,因为在tr上您将获得帖子列表的实例。参考下面的代码:

<a>
    <table class="table table-hover">
       <thead>
          <tr>
            <th>Name</th>
              </tr>
            </thead>
            <tbody>
              <tr  *ngFor="let post of posts" (click)="SelectedPost(post?.post_id)">
                <td>{{post.name}} </td>
              </tr>
            </tbody>
          </table>
        </a>

现在你将获得选中的帖子。你已经做过的其他事情。


0
投票

您可以将click事件绑定到Angular中的任何元素。您可以为事件分配一个函数,该函数应该分配帖子selectPost()

<tr  *ngFor="let post of posts">
    <td (click)="selectPost(post)">{{post.name}}</td>
</tr>

函数(在你的component.ts中)很简单,你使用post作为函数参数:

public selectPost(postToSelect: Post){
  this.selectedPost = postToSelect;
}

(您也可以直接设置selectedPost,如下所示:(click)="selectedPost = post"。但最好把它放在一个函数中)

© www.soinside.com 2019 - 2024. All rights reserved.