Angular 2 transclusion,指令内容为“alt”

时间:2016-08-22 04:46:14

标签: javascript html css angular

我这里有一个简单的问题,但找不到解决方案...... 所以这是我的logo.components.ts:

import {Component} from '../../../../frameworks/core/index';

@Component({
  moduleId: module.id,
  selector: 'my-logo',
  templateUrl: 'logo.component.html',
  styleUrls: ['logo.component.css']
})
export class LogoComponent  {}

所以我在home.component.ts中导入它:

import {LogoComponent} from '../../frameworks/mysite/components/logo/logo.component';

<my-logo>AltText</my-logo>

所以我的模板logo.component.html看起来像这样:

<div class="logo-icon">
  <img alt="" src="../../images/logo-icon.svg" />
</div>

所以我想要我的

<my-logo>AltText... or any content text from here.... </my-logo>

指令内容插入到我的logo.component.html中, <img alt="INSERTED HERE" src="../../images/logo-icon.svg" />

我知道

<ng-content></ng-content>

但在这种情况下,我不知道插入“alt”的正确方法...... 在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您不能转换为属性,只能转换为子元素。

您可以将值作为属性传递

StudentDetails.java:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_student_details);

   String IMAGE_URL = "http://xxx.xxx.xx.x/mobile_app/" + img_path + "/" + img_name;

    resultIv = (ImageView) findViewById(R.id.ProfilePicIV);
    new DownloadImageTask((ImageView) findViewById(R.id.ProfilePicIV))
            .execute(IMAGE_URL);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        Bitmap imageData = null;
        if (resultCode == RESULT_OK) {
            imageData = (Bitmap) data.getExtras().get("data");        
            Intent i = new Intent(this, Image.class);
            i.putExtra("name", imageData);         
            startActivityForResult(i,3);

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }
    } 
  else if (requestCode == 3) {
        onResume();
    }
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }
    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

@Override
public void onResume() {  
    // After a pause OR at startup
    super.onResume();
    getIntent();
    //Refresh your stuff here
    String img_name = getIntent().getStringExtra("img_name");
    String img_path = getIntent().getStringExtra("img_path");
    String IMAGE_URL = "http://xxx.xxx.xx.x/mobile_app/" + img_path + "/" + img_name;
    new DownloadImageTask((ImageView) findViewById(R.id.ProfilePicIV))
            .execute(IMAGE_URL);
}


StudentDetails.xml:
<ImageView
    android:id="@+id/ProfilePicIV"
    android:layout_width="120dp"
    android:layout_height="120dp"
    android:background="@drawable/man2"
    android:scaleType="fitXY" />

Image.java:

在您的组件中

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Bitmap bitmap = getIntent().getExtras().getParcelable("name");
    resultIv1.setImageBitmap(bitmap);
    resultIv.setImageBitmap(bitmap);

    String auid_t = getIntent().getStringExtra("auid_num");
    String imei_t = getIntent().getStringExtra("imei_num");
    auid_s.setText(auid_t);
    imei_s.setText(imei_t);

    text_position.setVisibility(View.GONE);
    doneBtn.setVisibility(View.GONE);
    doneBtn1.setVisibility(View.GONE);
    cancelBtn.setVisibility(View.GONE);
    text_upload.setVisibility(View.GONE);
    buttonUpload.setVisibility(View.GONE);
    buttonUpload1.setVisibility(View.GONE);
    cropView.setVisibility(View.GONE);
    toolbar1.setVisibility(View.GONE);
    toolbar.setVisibility(View.VISIBLE);
    resultIv.setVisibility(View.GONE);

    PassImageBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cropView.setVisibility(View.VISIBLE);
            resultIv.setVisibility(View.GONE);
            resultIv1.setVisibility(View.GONE);
            text_position.setVisibility(View.VISIBLE);
            doneBtn.setVisibility(View.VISIBLE);
            cancelBtn.setVisibility(View.VISIBLE);
            text_size.setVisibility(View.GONE);
            PassImageBtn.setVisibility(View.GONE);
            StampImageBtn.setVisibility(View.GONE);
            toolbar1.setVisibility(View.VISIBLE);
            toolbar.setVisibility(View.GONE);
            Bitmap photo = getIntent().getExtras().getParcelable("name");
            resultIv.setImageBitmap(photo);

            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
            Uri tempUri = getImageUri(getApplicationContext(), photo);
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(tempUri));
            int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 413, getResources().getDisplayMetrics());
            int y = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 531, getResources().getDisplayMetrics());
            cropView.of(Uri.fromFile(finalFile)).withAspect(x, y).initialize(Image.this);
        }
    });

    StampImageBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            cropView.setVisibility(View.VISIBLE);
            resultIv.setVisibility(View.GONE);
            resultIv1.setVisibility(View.GONE);
            text_position.setVisibility(View.VISIBLE);
            doneBtn1.setVisibility(View.VISIBLE);
            cancelBtn.setVisibility(View.VISIBLE);
            text_size.setVisibility(View.GONE);
            PassImageBtn.setVisibility(View.GONE);
            StampImageBtn.setVisibility(View.GONE);
            toolbar1.setVisibility(View.VISIBLE);
            toolbar.setVisibility(View.GONE);

            Bitmap photo = getIntent().getExtras().getParcelable("name");
            resultIv.setImageBitmap(photo);
            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
            Uri tempUri = getImageUri(getApplicationContext(), photo);
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(tempUri));
            int x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 56, getResources().getDisplayMetrics());
            int y = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 7, getResources().getDisplayMetrics());
            cropView.of(Uri.fromFile(finalFile)).withAspect(x, y).initialize(Image.this);
        }
    });

    doneBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final ProgressDialog dialog = ProgressDialog.show(Image.this, null, "Please wait…", true, false);
            cropView.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
            doneBtn.setVisibility(View.GONE);
            text_position.setVisibility(View.GONE);
            resultIv.setVisibility(View.VISIBLE);
            buttonUpload.setVisibility(View.VISIBLE);
            buttonUpload1.setVisibility(View.GONE);
            text_upload.setVisibility(View.VISIBLE);
            new Thread() {
                public void run() {
                    croppedBitmap = cropView.getOutput();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // cropped image set
                            resultIv.setImageBitmap(croppedBitmap);
                        }
                    });
                    Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
                    CropUtil.saveOutput(Image.this, destination, croppedBitmap, 1);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });
                }
            }.start();
        }
    });

    doneBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final ProgressDialog dialog = ProgressDialog.show(Image.this, null, "Please wait…", true, false);
            cropView.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
            doneBtn1.setVisibility(View.GONE);
            text_position.setVisibility(View.GONE);
            resultIv.setVisibility(View.VISIBLE);
            buttonUpload1.setVisibility(View.VISIBLE);
            buttonUpload.setVisibility(View.GONE);
            text_upload.setVisibility(View.VISIBLE);
            new Thread() {
                public void run() {
                    croppedBitmap = cropView.getOutput();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // cropped image set
                            resultIv.setImageBitmap(croppedBitmap);
                        }
                    });
                    Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
                    CropUtil.saveOutput(Image.this, destination, croppedBitmap, 1);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });
                }
            }.start();
        }
    });

    buttonUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage();
        }
    });
    buttonUpload1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            uploadImage1();
        }
    });

    pinButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            text_position.setVisibility(View.GONE);
            doneBtn.setVisibility(View.GONE);
            doneBtn1.setVisibility(View.GONE);
            cancelBtn.setVisibility(View.GONE);
            text_upload.setVisibility(View.GONE);
            buttonUpload.setVisibility(View.GONE);
            buttonUpload1.setVisibility(View.GONE);
            cropView.setVisibility(View.GONE);
            toolbar1.setVisibility(View.GONE);
            toolbar.setVisibility(View.VISIBLE);
            resultIv1.setVisibility(View.VISIBLE);
            resultIv.setVisibility(View.GONE);
            text_size.setVisibility(View.VISIBLE);
            PassImageBtn.setVisibility(View.VISIBLE);
            StampImageBtn.setVisibility(View.VISIBLE);

        }
    });

    pinButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            setResult(2, intent);
            finish();
        }
    });

    cancelBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            setResult(2, intent);
            finish();
        }
    });
}//end

private void uploadImage() {
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    Toast.makeText(Image.this, s, Toast.LENGTH_LONG).show();

                    resultIv.buildDrawingCache();
                    Intent intent = new Intent(Image.this, StudentDetails.class);
                    setResult(2, intent);
                    finish();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                    //Showing toast
                    Toast.makeText(Image.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(croppedBitmap);
            String auid_no = getIntent().getStringExtra("auid_num");
            String imei_no = getIntent().getStringExtra("imei_num");

            Map<String, String> params = new Hashtable<String, String>();
            //Adding parameters
            params.put(KEY_IMAGE, image);
            params.put(KEY_AUID, auid_no);
            params.put(KEY_IMEI, imei_no);

            return params;
        }
    };
    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void uploadImage1() {
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    Toast.makeText(Image.this, s, Toast.LENGTH_LONG).show();

                    resultIv.buildDrawingCache();
                    Intent intent = new Intent(Image.this, StudentDetails.class);

                    intent.putExtra("BitmapImage", croppedBitmap);
                    setResult(2, intent);
                    finish();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                    //Showing toast
                    Toast.makeText(Image.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage1(croppedBitmap);
            String auid_no = getIntent().getStringExtra("auid_num");
            String imei_no = getIntent().getStringExtra("imei_num");

            Map<String, String> params = new Hashtable<String, String>();
            //Adding parameters
            params.put(KEY_IMAGE, image);
            params.put(KEY_AUID, auid_no);
            params.put(KEY_IMEI, imei_no);

            return params;
        }
    };
    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //Adding request to the queue
    requestQueue.add(stringRequest);
}

public Uri getImageUri(Context inContext, Bitmap inImage) {
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

public String getStringImage(Bitmap bmp) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int width = 413;
    int height = 531;
    Bitmap bm = Bitmap.createScaledBitmap(bmp, width, height, false);
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

public String getStringImage1(Bitmap bmp) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int width = (int) 56.69;
    int height = (int) 70.87;
    Bitmap bm = Bitmap.createScaledBitmap(bmp, width, height, false);
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        Intent intent = new Intent();
        setResult(2, intent);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        finish();
    }
}

如果你仍然想要使用transclude,你可以使用<my-logo alt="AltText"></my-logo> 来转换它,从DOM中读取被转换的内容并将其分配给你绑定@Component({ template: ` <div class="logo-icon"> <img [alt]="alt" src="../../images/logo-icon.svg" /> </div> ` }) export class MyLogo { @Input() alt:string; } 的属性,但这非常麻烦。< / p>

更新 - 使用翻译

<ng-content>

获取已转换的内容

<img [alt]="...">