Angular CKEditor 5 添加自定义按钮点击 class

Angular CKEditor 5 add custom class on button click

我试图在单击元素工具栏上的按钮时将 class 添加到所选元素(在本例中为 table)。

       const dropdownView = createDropdown(locale);
        const model = editor.model;

        dropdownView.buttonView.set({
            label: "Table Style",
            icon: icon,
            tooltip: false
        });

        const items = new Collection();
        items.add({
            type: "button",
            model: new Model({
                id: "type1",
                withText: true,
                label: "Type 1"
            })
        });
        items.add({
            type: "button",
            model: new Model({
                id: "type2",
                withText: true,
                label: "Type 2"
            })
        });
        addListToDropdown(dropdownView, items);

        dropdownView.on("execute", function (eventInfo) {
            const type = eventInfo.source.id;
            model.enqueueChange("default", (writer) => {
                const selection = model.document.selection;
                const table = selection.getFirstPosition().findAncestor("table");

               // this not working. It works with keys like: height, width, but not with class
                writer.setAttribute("class", type, table);
            });
        });

无法添加自定义属性。如何添加 class 或数据集属性?

我找到的解决方案:

    const editor = this.editor;

    const comid = "tableClassAttribute";

    editor.model.schema.extend("table", { allowAttributes: comid });

    editor.ui.componentFactory.add("tableClass", (locale) => {
        const dropdownView = createDropdown(locale);
        const model = editor.model;

        dropdownView.buttonView.set({
            label: "Table Style",
            icon,
            tooltip: false
        });

        const items = new Collection();

        tableClasses.forEach((tableClass) => {
            items.add({
                type: "button",
                model: new Model({
                    id: tableClass.id,
                    withText: true,
                    label: tableClass.label
                })
            });
        });

        addListToDropdown(dropdownView, items);

        editor.conversion.attributeToAttribute({
            model: {
                name: "table",
                key: comid
            },
            view: {
                name: "figure",
                key: "class"
            }
        });

        dropdownView.on("execute", function (eventInfo) {
            model.enqueueChange("default", (writer) => {
                const type = eventInfo.source.id;
                const selection = model.document.selection;
                const table = selection.getFirstPosition().findAncestor("table");
                writer.setAttribute(comid, "table-" + type, table);
            });
        });

        return dropdownView;
    });