Angular:我想在加载元素时调用一个函数

时间:2018-01-19 07:01:56

标签: angular typescript

我想在加载元素时调用带参数的函数。 就像angualrjs中的nginit一样。我们可以在Angular 4中做到吗?

<div *ngFor="let item of questionnairelist"  (onload)="doSomething(item.id)" ></div>

我的打字稿功能:

doSomething(id) {
    console.log(id);
}

4 个答案:

答案 0 :(得分:3)

你需要写一个指令

import {Directive, Input, Output, EventEmitter} from '@angular/core';

@Directive({
  selector: '[ngInit]'
})
export class NgInitDirective {

  @Input() isLast: boolean;

  @Output('ngInit') initEvent: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
    if (this.isLast) {
      setTimeout(() => this.initEvent.emit(), 10);
    }
  }
}

在html中使用

<div *ngFor="let quetionnaireData of questionnairelist ; let $last = last" [isLast]='$last'
   (ngInit)="doSomething('Hello')"></div>

您也可以在app.module

中声明您的指令
@NgModule({
  declarations: [
    ..
    NgInitDirective 
  ],
  ......
})

答案 1 :(得分:2)

你的职能:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    public List<RecyclerItem> listItems;
    private Context mContext;


    public MyAdapter(List<RecyclerItem> listItems, Context mContext) {
        this.listItems = listItems;
        this.mContext = mContext;


    }
    @Override
    public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {

        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        view.setTag(getAdapterPosition());

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               final int position =    Integer.parse(v.getTag().toString());
                if (position == 0) {


                    Toast.makeText(mContext,"iOS",Toast.LENGTH_SHORT).show();

                }
                if (position == 1) {

                    Toast.makeText(mContext,"Android",Toast.LENGTH_SHORT).show();

                }

            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        final RecyclerItem itemList = listItems.get(position);
        holder.txtTitle.setText(itemList.getTitle());
        holder.txtDescription.setText(itemList.getDescription());
        holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Display option menu
                PopupMenu popupMenu = new PopupMenu(mContext, holder.txtOptionDigit);
                popupMenu.inflate(R.menu.option_menu);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        switch (item.getItemId()) {
                            case R.id.mnu_item_save:
                                Toast.makeText(mContext, "Saved " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
                                break;
                            case R.id.mnu_item_delete:
                                //Delete item
                                Toast.makeText(mContext, "Deleted " + listItems.get(position).getTitle(), Toast.LENGTH_SHORT).show();
                                listItems.remove(position);
                                notifyDataSetChanged();
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                });
                popupMenu.show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return listItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private  Button buttoncalling;
        public TextView txtTitle;
        public TextView txtDescription;
        public TextView txtOptionDigit;
        public ViewHolder(View itemView) {
            super(itemView);
            txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
            txtDescription = (TextView) itemView.findViewById(R.id.txtDescription);
            txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
            buttoncalling  = (Button) itemView.findViewById(R.id.bbbbbbbbbb);
            buttoncalling.setOnClickListener(this);


        }

        @Override
        public void onClick(View view) {

        }
    }
}

如果要传递在组件本身中声明的参数并从组件设置,请尝试如下:

ExecuteMyFunction(value:any):void{
    console.log(value);
}

如果您将变量设置为输入参数并从其他组件设置,请尝试按以下步骤操作:notificationMessage:string=''; @Input() message:string; ngAfterViewInit(){ this.ExecuteMyFunction(this.notificationMessage); } 每次更改ngOnChanges变量值时都会触发。

Input

答案 2 :(得分:1)

使用ngOnInit()和@Input指令。 例如,在您的子组件中:

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

@Component({
  selector: 'my-component',
  template: `
  <h3>My id is: {{itemId}}</h3>
  `
})


export class MyComponent implements OnInit
{
  @Input() itemId: string;

  //other code emitted for clarity

  public ngOnInit(): void
  {
    // Now you can access to the itemId field e do what you need
    console.log(this.itemId);     
  }
}

在您的父组件

<div *ngFor="let item of questionnairelist">
    <my-component itemId='{{item.Id}}'></my-component>
</div>

答案 3 :(得分:-1)

import { Router,NavigationEnd } from '@angular/router';


constructor( private router: Router ) {
 this.router.events.subscribe((e) => {
   if (e instanceof NavigationEnd) {
       // Function you want to call here
   }
 });
}